$("#id") 和 $("[id=]") 的区别 [英] Difference between $("#id") and $("[id=]")

查看:79
本文介绍了$("#id") 和 $("[id=]") 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的页面中,由于某种原因(我认为这与主题无关,因此不解释)一个 div 被复制,并且在我的 html 中生成了两个具有相同 id 的 div.在编写 jquery 代码以删除除最顶层之外的所有 div 时,我发现 $("#id") 只返回了 1 个元素(注意:现在有两个具有相同 id 的 div)而 $("[id=]") 返回给我 2.所以最后我的代码使用了 $("[id=]") 而不是 $("#id").有什么理由吗?$("#id") 是否只返回它找到的具有指定 id 的第一个元素?

In my page, due to some reason (which I do not find relevant to the topic hence not explaining) a div gets duplicated and two divs with same id are generated in my html. While writing jquery code to remove all divs except topmost, I found that $("#id") was returning me just 1 element(note: there are two divs with same id now) whereas $("[id=]") was returning me 2. So finally my code worked with $("[id=]") but not with $("#id"). Any reason why? Is it that $("#id") returns only the first element it finds with specified id?

请注意,我已经遇到了一个 thread 有类似问题但没有回答我的查询

Please note that I have already come across a thread which has a similar question but does not answer my query

推荐答案

事情是 $("#id") 总是会给你一个结果,比如 document.getelementById() 但是,当您执行 $("[id=]") 时,您会找到具有给定属性的所有元素 id,因此它会返回多个元素,因为它没有现在不要使用 javascript document.getelementById().

The thing is $("#id") will always gives you single result like document.getelementById() however when you do $("[id=]") you are finding all elements with a given attibute as id so it returns you multiple elements since it doesn't use the javascript document.getelementById() now.

$("[id=]") 是当你想从你的文档中选择一些遵循一些规则的元素时使用的东西,比如

$("[id=]") is something that you use when you want to select some elements form your document that follow some rules like

属性包含选择器 [name*="value"]

Attribute Contains Selector [name*="value"]

选择具有包含给定子字符串的值的指定属性的元素.

Selects elements that have the specified attribute with a value containing a given substring.

属性包含单词选择器 [name~="value"]

Attribute Contains Word Selector [name~="value"]

选择具有指定属性的元素,其值包含给定的单词,以空格分隔.

Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.

属性以选择器结束 [name$="value"]

Attribute Ends With Selector [name$="value"]

选择具有指定属性的元素,其值恰好以给定的字符串结尾.比较区分大小写.

Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.

等等.

有关更多信息,请参阅https://api.jquery.com/category/selectors/但是,在您的 HTML 中,您最好将 id 保持为 唯一.如果您希望多个元素具有相同的 id,请改用 class.

For more information see https://api.jquery.com/category/selectors/ However in you HTML you should ideally keep the id to be unique. If you want multiple elements to have same id then use class instead.

这篇关于$("#id") 和 $("[id=]") 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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