gpt4 book ai didi

javascript - 动态添加div及其内容

转载 作者:行者123 更新时间:2023-11-28 17:32:10 27 4
gpt4 key购买 nike

<div class='tagstore' id='tagstore'>
<div class='tagsingle' title='delete'>323</div>
<div class='tagsingle' title='delete'>525</div>
</div>

我需要添加以下内容:

<div class='tagsingle' title='delete'>some variable</div>

js

var a = 'lorem';
var obj = "<div class='tagsingle' title='delete'>" + a + "</div>";
obj.appendTo('#tagstore');

错误: obj.appendTo is not a function...

还尝试过:

var obj = document.createElement('div');
obj.className = 'tagsingle';
obj.appendTo('#tagstore');

错误: obj.appendTo is not a function...

有什么帮助吗?

最佳答案

您的主要问题是您正在普通 JavaScript 对象上调用 JQuery 方法。

有很多方法可以实现您想要做的事情:

在JQuery中,有.append() ,但您必须在新元素应附加到的对象上调用 .append(),而不是您要附加的对象:

var a = 'lorem';
var obj = "<div class='tagsingle' title='delete'>" + a + "</div>";
$("#tagstore").append(obj);

// Or, you can combine the creation of the string and the append:
$("#tagstore").append("<div class='tagsingle' title='delete'>" + a + "</div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tagstore' id='tagstore'>
<div class='tagsingle' title='delete'>323</div>
<div class='tagsingle' title='delete'>525</div>
</div>

而且,还有.appendTo() ,但您必须在 JQuery 对象上调用它,并将 JQuery 对象作为要附加到的对象传递,而不仅仅是选择器:

var a = 'lorem';
var obj = "<div class='tagsingle' title='delete'>" + a + "</div>";
$(obj).appendTo($('#tagstore'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tagstore' id='tagstore'>
<div class='tagsingle' title='delete'>323</div>
<div class='tagsingle' title='delete'>525</div>
</div>

要插入包含一些 HTML 的字符串,在普通 JavaScript 中,它是 .innerHTML :

var a = "Lorem";
document.getElementById("tagstore").innerHTML += "<div class='tagsingle' title='delete'>" + a + "</div>";
<div class='tagstore' id='tagstore'>
<div class='tagsingle' title='delete'>323</div>
<div class='tagsingle' title='delete'>525</div>
</div>

但是,.innerHTML 需要构建字符串,并且存在安全和性能问题。使用 DOM API,您 create a new DOM node ,配置它,然后使用 .appendChild() 将其添加到文档中:

var a = 'lorem';
var obj = document.createElement("div");
obj.classList.add('tagsingle');
obj.title='delete';
obj.textContent = a;
document.getElementById("tagstore").appendChild(obj);
<div class='tagstore' id='tagstore'>
<div class='tagsingle' title='delete'>323</div>
<div class='tagsingle' title='delete'>525</div>
</div>

关于javascript - 动态添加div及其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50070303/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com