What happens when I use the following, and is there any semantic difference?
Method one:
var task = $('<li class="task"><header><h1></h1></header></li>')
$('#backlog-tasks').append(task);
Method two:
var task = $('<li>').attr('class','task');
task.append('<header>');
.....
A secondary question: Is there an approach which you favour over the above?
Example
http://jsfid开发者_StackOverflow社区dle.net/Zwedh/2/
As noted in the jQuery documentation, method 1 is parsed by the browser, while method 2 isn't. This is rather hard to find in the prose,
...jQuery uses the browser's
.innerHTML
property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as<html>
,<title>
, or<head>
elements. As a result, the elements inserted may not be representative of the original string passed.
but it definitely is there. (Emphasis mine.)
I tend to use method 2, for several reasons:
- Doesn't rely on possibly-browser-specific stuff. (See above.)]
- You don't have to worry about quoting quotes - jQuery does it for you.
- What if you need an attribute's contents to be user-defined?
More on that last one. Say you need to set the style
of some element according to user input (probably implausible, but I couldn't think of a better example).
Method 1
$("<p style='" + input + "'>")
Now think about an input
of ' onclick="$.ajax(/* some evil parameters */)" data-dummy='
. (Or I'm sure you can think of worse.) Not the most desirable thing ever.
Method 2
$("<p>").attr("style", input)
Much better.
精彩评论