$(“#id")和$("[id =]")之间的差异 [英] Difference between $("#id") and $("[id=]")

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

问题描述

在我的页面中,由于某种原因(我发现与该主题无关,因此不作解释),一个div被复制,并且在我的html中生成了两个具有相同id的div.在编写用于删除除最顶部以外的所有div的jquery代码时,我发现$("#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?

请注意,我已经遇到过

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天全站免登陆