jQuery 查找 id 开头的 html 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2298730/
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
Find html element which id starts with
提问by lidermin
my question is this:
我的问题是:
I have HTML code in multiple pages, on each of them I used a JQgrid (jquery grid) for display some data. I knew that on each of those pages, the element that holds the JQgrid is named as "LIST_xxx". Now I need to make a javascript that takes that element "LIST_XXXX" on each page and does some stuff. How could I search for an element by ID but only knowing its initial part (of the ID ,like i mentioned previously):
我在多个页面中有 HTML 代码,在每个页面上我使用 JQgrid(jquery 网格)来显示一些数据。我知道在每个页面上,包含 JQgrid 的元素都被命名为“LIST_xxx”。现在我需要制作一个 javascript,在每个页面上使用该元素“LIST_XXXX”并执行一些操作。我怎么能通过 ID 搜索一个元素,但只知道它的初始部分(ID 的,就像我之前提到的那样):
$('#list_[XXXX]')... --> The part surrounded by [] is variable on each page, i want to discriminate that.
I hope i made myself clear. Thanks.
我希望我说清楚了。谢谢。
回答by Glen Little
Try
尝试
$('div[id^="list_"]')
It should work
它应该工作
回答by SLaks
You need to use the attribute starts with selector, like this:
您需要使用以 selector 开头的属性,如下所示:
$('[id^=list_]').whatever()
回答by Yuriy Faktorovich
Give that element a common class name or some other attribute you can query for.
为该元素指定一个公共类名称或其他一些您可以查询的属性。
回答by Chetan Sastry
Use the "attribute starts with" selector http://api.jquery.com/attribute-starts-with-selector/
使用“属性开头”选择器http://api.jquery.com/attribute-starts-with-selector/
$("[id^=list_]")
Be aware that this is inefficient. Prefix with the tag name and descend from the nearest parent if possible.
请注意,这是低效的。如果可能,使用标签名称作为前缀并从最近的父代开始下降。
回答by Haroon Khalid
To get an element ending with a certain id/character
获取以某个 ID/字符结尾的元素
find('[id$=someid]')
To get an element starting with a certain id/character
获取以特定 ID/字符开头的元素
find('[id*=anotherid]')
To get an element matching with a certain id/character
获取与某个 ID/字符匹配的元素
find('[id^=id]')