jQuery 只匹配 div 中的一部分 id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4743860/
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
jQuery match only part of id from div
提问by I-M-JM
I ran into an unusual situation yesterday night.
昨天晚上我遇到了一个不寻常的情况。
I need to match only part of id. Let me clear you all with an example
我只需要匹配 id 的一部分。举个例子让大家一目了然
I have few divs like
我有几个像
<div id="sales_info_1">... ...... ...... ...... ...</div>
<div id="sales_info_2">... ...... ...... ...... ...</div>
<div id="sales_info_3">... ...... ...... ...... ...</div>
and jQuery goes like
和 jQuery 一样
jQuery("div#dont_know_what_to_write_here").bind("click", function(){
... ...... ...... ...... ...
});
I need to match only sales_info, ignoring _1, _2 or _anything, can anyone suggest me how to achieve this?
我只需要匹配sales_info,忽略 _1、_2 或 _anything,谁能建议我如何实现这一点?
Thanks
谢谢
回答by deceze
You could use the "Starts With" selector:
您可以使用“开头为”选择器:
$('div[id^="sales_info_"]')
I'd rather recommend you use a unique class name for your elements that you can select on though.
我宁愿建议您为您可以选择的元素使用唯一的类名。
回答by Chuck Callebs
Alternatively, add class="sales_info"
to your HTML mark-up.
或者,添加class="sales_info"
到您的 HTML 标记中。
Then, do this:
然后,这样做:
$(".sales_info").bind("click", function() {
...
}
回答by ashish.chotalia
Try with this
试试这个
$("div[id^='sales_info_']").bind( ... );
回答by Phrogz
You want the attribute starts with selector:
您希望属性以 selector 开头:
$('div[id^="sales_info"]').bind( ... );
回答by fesh
You can use css selector
您可以使用 css 选择器
try this code
试试这个代码
html
html
<div id="sales_info_1"></div>
<div id="user_info_1"></div>
<div id="sales_info_2"></div>
<div id="user_info_2"></div>
<div id="sales_info_3"></div>
<div id="user_info_3"></div>
css
css
.red{
display:block;
float:left;
width:50px;
height:20px;
background-color:#FF0000;}
.blue{
display:block;
float:left;
width:50px;
height:20px;
background-color:#0000FF;}
jquery
查询
$('div[id^="sales"]').addClass('red');
$('div[id^="user"]').addClass('blue');
css selector ^=
will select div with ID that start with the specified value and add the css style.
css 选择器^=
将选择 ID 以指定值开头的 div 并添加 css 样式。