计算具有相同 id 的 div 元素 JQUERY

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19898896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:46:44  来源:igfitidea点击:

count div elements with the same id JQUERY

jqueryhtmlcss

提问by leeshin

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

我创建了多个具有相同 ID 的DIV。我想通过使用JQUERY来跟踪DIV 的数量。这个好像行不通。

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

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

即使有多个结果,结果也始终为1

回答by Sasidharan

Give class name for div and paste the below code.. It will give the count.

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

var conveniancecount = $("div[class*='conveniancecount']").length;

回答by sachinjain024

Having same id multiple times is not recommended by W3C. See what they say about it.

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

The id attribute specifies a unique idfor an HTML element (the id attribute value must be unique within the HTML document). The id attribute can be used to point to a style in a style sheet. The id attribute can also be used by a JavaScript (via the HTML DOM) to make changes to the HTML element with the specific id.

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

Suggestion:

建议:

Use class name for all the divs you want to group and use this selector:

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

$('.myClassName')

See these references for more:

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

1. Why do Ids need to be unique

1.为什么ID需要唯一

回答by Alberto Soto

Maybe this can be useful for you:

也许这对你有用:

I've been making inner ajax calls wich may be the container starts wrapping inside one time and another in some cases. I resolve it with this:

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

Search for your container target container with a query with this selector, instead of '#yourWrapper':

使用此选择器而不是“#yourWrapper”进行查询来搜索您的容器目标容器:

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

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

Try unwrapping it, because you shouldn't have repeated ID's on your DOM

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

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

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

Hope it helps you

希望对你有帮助

Regards!

问候!