I have a simple function in jQuery tha开发者_JAVA百科t creates new elements in the DOM. the problem is in the html source code, it append every element in the same line, and it's very bad to read.
function _loadNewElements(elements){
for(var i=0; i<elements.length; i++){
var fixedElement = $('<img />')
var position = elements[i].position;
var cssMap = {
'position': 'fixed',
'top': position.top + "px",
'left': position.left + "px"
};
fixedElement.css(cssMap);
fixedElement.addClass("fixedTag");
fixedElement.attr('alt', elements[i].text);
fixedElement.attr('src', "elements/" + elements[i].id + ".png");
fixedElement.appendTo($('#board'));
//i'd like to print something here like ("\n");
}
}
I tried document.write("\n")
but in this context it doesn't work.
Any solution?
You can change this:
fixedElement.appendTo($('#board'));
I would cache the board selector outside your loop, like this:
var board = $('#board');
Then in your loop, replace the above with:
board.append(fixedElement).append('\n');
This will give you a new-line in the source and speed up your loop, since it's not looking for #board
every time. If you're using jQuery 1.4, you can use $(html, props)
to shorten it all down to this:
function _loadNewElements(elements){
var board = $('#board');
for(var i=0; i<elements.length; i++){
$('<img />', {
css : { 'position': 'fixed',
'top': elements[i].position.top + "px",
'left': elements[i].position.left + "px" },
'class': "fixedTag",
'alt': elements[i].text,
'src': "elements/" + elements[i].id + ".png"
}).appendTo(board);
board.append('\n'); //Add new-line for your source view
}
}
Did you try \r\n
? I believe that's the UTF-8 method of newline.
精彩评论