选择具有以特定值开始/结束的id属性的元素 [英] Select elements with id attribute that starts/ends with a particular value
问题描述
我有以下几段:
< p id =item5_2> A< / p>
< p id =item9_5> B< / p>
< p id =item14_2> C< / p>
我想改变id开头的段落内容 item
结尾于
2
。
我使用了以下jQuery:
$(#item [\ d] * 2)。html(D);
但它不起作用。我怎样才能使它工作?
是的,您可以将属性以开始,而属性以选择符结束
$('[id ^ =item] [id $ =2]')。html(D);
FIDDLE (您必须在小提琴中启用jQuery)
你不能使用正则表达式然而,匹配之间的数字,因为你需要 filter()
$('[id ^ =item]')。filter(function(){
返回this.id.match(/ item \d + _2 /);
})。html(D);
Can jQuery or JavaScript be used with a regex to select multiple elements with similar id?
I have the following paragraphs:
<p id="item5_2"> A </p>
<p id="item9_5"> B </p>
<p id="item14_2"> C </p>
I want to change the content of paragraphs with id starting in item
and ending in 2
.
I used the following jQuery:
$("#item[\d]*2").html("D");
but it doesn't work. How can I get it to work?
Yes it can, you can combine the attribute starts with and the attribute ends with selector
$('[id^="item"][id$="2"]').html("D");
FIDDLE (and you have to enable jQuery in the fiddle)
you can't use regex to match the numbers in between though, for that you'd need filter()
$('[id^="item"]').filter(function() {
return this.id.match(/item\d+_2/);
}).html("D");
这篇关于选择具有以特定值开始/结束的id属性的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!