jQuery create element containing child element

Creating a div element in jQuery does a good job on describing how to create and insert an element, however, I wish to create an element with a child element such as <li><a href="abc.html">click</a></li> . The href and text is susceptible to XSS, so I need take steps. I could create the <a> element like:

var href='abc.html',text='click';
jQuery('<a/>', {
    href: href,
    text: text
}).appendTo('#mySelector');

How do I modify this to include the </li> element?


wrap it up:

$(document).ready(function() {
  var href='abc.html',text='click';

jQuery('<a/>', {
    href: href,
    text: text
}).wrap("<li>").parent().appendTo('#mySelector');


})

http://codepen.io/anon/pen/Eyqco


Personnaly,我喜欢直接在html中完成:

var html = "";
html += "<li>";
html += "<a href='www.google.com' >click me</a>";
html += "</li>";

$("myselector").append(html);

Firstly you could append the <li> tag to the element with the id mySelector .

$('<li>').appendTo('#mySelector');

Then you append your <a> tag to the li element.

链接地址: http://www.djcxy.com/p/83366.html

上一篇: 在jquery中创建一个元素

下一篇: jQuery创建包含子元素的元素