简体   繁体   中英

Creating HTML elements with jQuery: what’s the correct approach?

Recently I did a Backbone tutorial over on Tuts+ and I saw a really weird way of creating a HTML element with jQuery, the author was saying to create it like this:

var select = $('</select>', {
    html: '<option value="all">All</option>'
});

But I thought that it was definitely incorrect so I just changed the select element to have no forward slashes:

var select = $('<select>', {
    html: '<option value="all">All</option>'
});

So after I finished the tutorial, I took a look at the comments and one commenter said the it should be written like this:

var select = $('<select/>', {
    html: '<option value="all">All</option>'
});

This worked fine too but I'm confused: what is the difference between the three? I'm sure the first one ( </select> ) doesn't work but what is the advantage of using <select/> over <select> ? Does it even make a difference?

Thanks in advance.

The first one on your list won't work, the other two both work the same.

Personally, I prefer to use <select> because to me that's the most readable. If you prefer to put the slash in, go for it - it will work just fine, it's just a matter of readability.

You can also use $("<select></select>") if you like, although to me that's messier again.

Also, for adding options, it's better to add them like you are doing the select, rather than coding the raw html as a string, eg:

var options = [];

for (var i = Options.length - 1; i >= 0; i--) {
    options.push($("<option>", {
       html: Options[i].Title,
       value: Options[i].Value
    }));
}

var select = $("<select>", {
    html: options,
    id: "OptionSelector"
});

As pointed out by David below, $("<select>") is the correct way according to the documentation, so it probably is better to do it that way, despite the behaviour of the other ways working in my (limited) tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM