使用JQuery追加,我想用HTML填充一个div,对于页面上相同类的所有实例都一样。
Text
<div class="custom-content"></div>
Text
<div class="custom-content"></div>
Text
<div class="custom-content"></div>
TextJQuery:
<script>
if ($(window).width() < 500) {
$(".custom-content").append("<script>document.write('Small');<\/script>");
} else {
$(".custom-content").append("<script>document.write('Large');<\/script>");
}
</script>我预计“大”或“小”会出现在所有3个div上,如下所示:
预期输出:
Text
<div class="custom-content">Large</div>
Text
<div class="custom-content">Large</div>
Text
<div class="custom-content">Large</div>
Text只有当我重复脚本3次,它做我所期望的,这是一个糟糕的解决方案。
演示: https://codepen.io/MichaelROS/pen/QWwgXEB
我能做什么?请不要建议使用与附件不同的功能。
注意:代码很长,它不只是写一个单词,我这样做是为了说明这个例子中已经存在的问题。
发布于 2019-12-26 00:21:26
最重要的是循环。故事:获取具有这个类的元素。那就做个循环。并为每个元素添加子元素。
在这一点上有不同的解决方案。
我给你几把钥匙:- jQuery.each function - document.getElementsByClassName
下面是一个类似的问题。jQuery .text() multiple elements same class
我希望我能帮上忙
发布于 2019-12-26 04:21:03
参见:https://www.w3schools.com/jsref/met_doc_write.asp,它声明:
write()方法主要用于测试:如果它是在HTML文档完全加载后使用的,它将删除所有现有的HTML.。
(强调我的)它只是第一次被调用,因为在那之后,文档不再包含正在执行的代码。我不确定您到底想要完成什么,但是document.write可能不是最好的解决方案。
发布于 2019-12-27 13:00:37
我想明白了。它是附加的,脚本标记很好,只是没有在其中执行脚本。所以我采取了另一种方法:
新
Text
<div class="custom-content"><script>customtag();</script></div>
Text
<div class="custom-content"><script>customtag();</script></div>
Text
<div class="custom-content"><script>customtag();</script></div>
Text新JS:
function customtag() {
if ($(window).width() < 500) {
document.write('Small');
} else {
document.write('Large');
}
}https://stackoverflow.com/questions/59482690
复制相似问题