jQuery('#id').length是否总是返回1? [英] Does jQuery('#id').length always return 1?

查看:67
本文介绍了jQuery('#id').length是否总是返回1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难弄清楚为什么为什么在计数页面中具有相同id的元素时.length总是总是返回1.我确实知道html文档中应该只包含具有唯一html id的元素,但是在我正在从事的项目中,用户可能会无意中添加重复项.

I am having trouble figuring out why .length always seems to return 1 when counting elements having the same id in the page. I do know that there should only be elements with unique html id's in an html document, but in the project I am working on, the user may inadvertently add duplicates.

那么,jQuery在计数元素id时总是返回1是正常的行为吗?

So, is it the normal behaviour for jQuery to always return 1 when counting elements id's?

<div id="1">foo</div>
<div id="1">foo</div>

jQuery(function(){
   alert(jQuery('#1').length); // returns 1
});

我在这里建立了一个示例: http://jsfiddle.net/eSNZx/

I have built an example here: http://jsfiddle.net/eSNZx/

感谢您的帮助

推荐答案

返回0或1.具有相同ID的多个元素无效.

Returns 0 or 1. Multiple elements with the same id is not valid.

这不是jQuery或javascript限制,而是HTML限制.检查 7.5.2元素标识符:id和class属性官方说法.

It's not a jQuery or javascript restriction but HTML one. Check 7.5.2 Element identifiers: the id and class attributes for official word about that.

这篇关于jQuery('#id').length是否总是返回1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆