这是我的 jquery,我试图在 abc div 类中添加新数据
var html = '<div class="wrapper"><div class="abc"></div></div>';
if (someData == "YES"){
var newHTML = '<div>hello</div>';
$(html).find(".abc").html(newHTML);
}
$(body).html(html);
如何获取更新的 HTML?
最佳答案
问题是因为您从 html
中的字符串创建了一个 jQuery 对象,并且修改了该对象,但没有在任何地方存储对其的引用。
当您调用 $(body).html()
时,您将附加原始字符串,而不是您更改的 jQuery 对象。因此,您需要将逻辑更改为:
var html = '<div class="wrapper"><div class="abc"></div></div>';
var $html = $(html); // create the jQuery object and store a reference to it
// alternatively the above can be made in to one line:
// var $html = $('<div class="wrapper"><div class="abc"></div></div>');
if (someData == "YES") {
var newHTML = '<div>hello</div>';
$html.find(".abc").html(newHTML); // amend the jQuery object
}
$(body).html($html); // add the updated HTML to the DOM
关于jquery - 尝试在 DIV 中添加内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58483215/