9

I created a more than one DIV with the same ID. I want to keep track of the number of DIV's by using JQUERY. This one does not seem to work.

var divid = "123456";
var count_id_len = $("#parentdiv").find("#"+divid).length;
console.log(count_id_len);

The result is always 1 even though there is more than one of them.

4

3 回答 3

15

为 div 提供类名并粘贴以下代码。它会给出计数。

var conveniancecount = $("div[class*='conveniancecount']").length;
于 2013-11-11T04:39:49.483 回答
3

也许这对您有用:

我一直在进行内部 ajax 调用,这可能是容器在某些情况下一次又一次地开始包裹。我用这个解决它:

jQuery("div[id='yourWrapper_1']").length

尝试打开它,因为你不应该在你的 DOM 上有重复的 ID

http://api.jquery.com/unwrap/

希望对你有帮助

问候!

于 2015-01-12T10:21:56.573 回答
3

W3C 不建议多次使用相同的 id。看看他们怎么说。

id 属性为 HTML 元素指定一个唯一的 id(id 属性值在 HTML 文档中必须是唯一的)。id 属性可用于指向样式表中的样式。JavaScript(通过 HTML DOM)也可以使用 id 属性来更改具有特定 id 的 HTML 元素。

建议:

为要分组的所有 div 使用类名并使用此选择器:

$('.myClassName')

有关更多信息,请参阅这些参考资料:

1.为什么ID需要唯一

于 2013-11-11T04:50:10.550 回答