开发者

Proper mechanism to add elements using jQuery

开发者 https://www.devze.com 2023-02-10 11:09 出处:网络
I\'m using jQuery to add elements dynamically to a dropdown but I thin开发者_如何学Pythonk I\'m mixing syntaxes and would like to go pure jQuery.Currently I\'m doing this:

I'm using jQuery to add elements dynamically to a dropdown but I thin开发者_如何学Pythonk I'm mixing syntaxes and would like to go pure jQuery. Currently I'm doing this:

$("#data-source-menu").addClass("menu-container") .html($("<ul class=\"popup-menu\" id=\"dataset-menu\"><\/ul>"));

Then later

$("#dataset-menu").append($("<div>" + dataset.label + "<\/div>").addClass("menu-item").attr(dataset));

It's that inner building of the html I don't like. Is there a more abstract way to approach this that doesn't involve writing html? Something like JavaScript's document.createTextNode("Hello")?


That should be better:

$('#data-source-menu').addClass('menu-container').html(
    $('<ul/>').addClass('popup-menu').attr('id', 'dataset-menu').append(
        $('<div/>').text(dataset.label).addClass('menu-item')
    )
);

and here's the live demo.

0

精彩评论

暂无评论...
验证码 换一张
取 消