jQuery 选择器中的通配符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5376431/
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
Wildcards in jQuery selectors
提问by ziiweb
I'm trying to use a wildcard to get the id of all the elements whose id begin with "jander". I tried $('#jander*')
, $('#jander%')
but it doesn't work..
我正在尝试使用通配符来获取 id 以“jander”开头的所有元素的 id。我试过了$('#jander*')
,$('#jander%')
但它不起作用..
I know I can use classes of the elements to solve it, but it is also possible using wildcards??
我知道我可以使用元素的类来解决它,但也可以使用通配符??
<script type="text/javascript">
var prueba = [];
$('#jander').each(function () {
prueba.push($(this).attr('id'));
});
alert(prueba);
});
</script>
<div id="jander1"></div>
<div id="jander2"></div>
回答by nico
To get all the elements starting with "jander" you should use:
要获取以“jander”开头的所有元素,您应该使用:
$("[id^=jander]")
To get those that end with "jander"
得到那些以“jander”结尾的
$("[id$=jander]")
See also the JQuery documentation
另请参阅JQuery 文档
回答by Martijn Smidt
Since the title suggests wildcard you could also use this:
由于标题建议通配符,您也可以使用它:
$(document).ready(function(){
console.log($('[id*=ander]'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jander1"></div>
<div id="jander2"></div>
This will select the given string anywhere in the id
.
这将选择id
.
回答by GoatInTheMachine
Try the jQuery starts-with
尝试使用 jQuery 开头
selector, '^=', eg
选择器, '^=', 例如
[id^="jander"]
I have to ask though, why don't you want to do this using classes?
我不得不问,为什么你不想用类来做这个?
回答by l3thal
for classes you can use:
对于您可以使用的课程:
div[class^="jander"]
回答by PJ Brunet
To get the idfrom the wildcard match:
要从通配符匹配中获取 id:
$('[id^=pick_]').click(
function(event) {
// Do something with the id # here:
alert('Picked: '+ event.target.id.slice(5));
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pick_1">moo1</div>
<div id="pick_2">moo2</div>
<div id="pick_3">moo3</div>
回答by eduard
When you have a more complex id string the double quotes are mandatory.
当您有更复杂的 id 字符串时,双引号是强制性的。
For example if you have an id like this: id="2.2"
, the correct way to access it is: $('input[id="2.2"]')
例如,如果您有这样的 id: id="2.2"
,则访问它的正确方法是:$('input[id="2.2"]')
As much as possible use the double quotes, for safety reasons.
为安全起见,尽可能使用双引号。