[英]Why is this small javascript not working?
I have multiple instances of a div with an id of "myDiv" on a page. 我在页面上有一个ID为“ myDiv”的div的多个实例。 I want to replace the contents of these divs.
我想替换这些div的内容。 When I use this javascript:
当我使用此javascript时:
function replaceContent(id, content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
replaceContent('myDiv', 'hello there');
<div id="myDiv"></div>
<div id="myDiv"></div>
<div id="myDiv"></div>
It only replaces the content inside one of those divs and not all of them. 它仅替换其中一个div中的内容,而不是全部替换。 If I use the .html() function of jquery instead, it replaces the contents of all divs.
如果我改用jquery的.html()函数,它将替换所有div的内容。 Is there any way I can get the above js to work in the same way?
有什么办法可以使上述js以相同的方式工作?
id值必须唯一-您不能有多个同名的id并更新所有ID。
I have multiple instances of a div with an id of "myDiv" on a page.
我在页面上有一个ID为“ myDiv”的div的多个实例。
This is where you're doing it wrong. 这是您做错了的地方。 You cannot assign an ID to multiple elements on a page - it has to be unique.
您不能将ID分配给页面上的多个元素-它必须是唯一的。
It only replaces the content inside one of those divs and not all of them.
它仅替换其中一个div中的内容,而不是全部替换。
This happens because getElementById()
returns only the first-matched element in case multiple such elements are matched. 发生这种情况是因为在多个这样的元素被匹配的情况下,
getElementById()
仅返回第一个匹配的元素。
To solve this, assign a class instead of an ID to the divs you want to target, and if you can use jQuery, use this instead (assuming class="myDiv"
): 要解决此问题,请为您要定位的div分配一个类而不是ID ,如果可以使用jQuery,请改用它(假设
class="myDiv"
):
function replaceContent(className, content) {
$('div.' + className).html(content);
}
// This appends className so the selector becomes $('div.myDiv')
replaceContent('myDiv', 'hello there');
IDs have to be unique. ID必须是唯一的。 You can use the same class name for all divs and then use a css selector.
您可以对所有div使用相同的类名,然后使用css选择器。
<div id="div1" class="mydivs">blah</div>
<div id="div2" class="mydivs">blah123</div>
For eg In JQuery, you could do: 例如,在JQuery中,您可以执行以下操作:
$('.mydivs').html("whatever");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.