mardi 22 avril 2014

Inserting Large Blocks of HTML without Modification


Vote count:

0




I am performing DOM manipulation and need to insert fairly large blocks of HTML and was wondering if there was a better way of doing so beyond concatenation or a jumbled mess of code. Take the fairly simple code below:



<div id="mydiv">
<img src="image1.jpg" />
<a href="page1.html" onclick="myfunction('test');">Here's My Link</a>
</div>


I know of two ways to insert the HTML inside of a page – both require manually escaping single quotes:


Concatenate the String



$('#mydiv').after( //html, innerHtml, insertAfter, etc. can be used here
'<div id="mydiv">' +
'<img src="image1.jpg" />' +
'<a href="page1.html" onclick="myfunction(\'test\');">Here\'s My Link</a>'+
'</div>'
);


Remove Line Breaks



$('#mydiv').after('<div id="mydiv"><img src="image1.jpg" /><a href="page1.html" onclick="myfunction(\'test\');">Here\'s My Link</a></div>');


My code example is very short but it’s easy to see neither of these two processes scale very well once you get above 10 lines or code or JavaScript calls that have to be escaped. From a work flow perspective, it is really time consuming to write/test code then manually convert it to one of the methods above. Furthermore, it becomes incredibly difficult to debug or add code within this jumbled mess on a future date – the line break version is barely readable.


With all of these JS/jQuery enhancements – is there really no way to efficiently account for multi-line strings?? How do people who have to do this on a fairly routine basis deal with this? If something can’t be done in JS, is there some online tool that will convert code to and from (including escaped characters) one of these options (sort of like what JS minifiers do)?


Thanks



asked 26 secs ago






Aucun commentaire:

Enregistrer un commentaire