在我的文档中,我有几个 ID 以字母“p”开头然后是任意数字的 div。我想使用 jQuery 正则表达式模式找到它们,然后向它们添加类。你能帮我修复这个片段吗?谢谢。
$(function(){
var pattern = "#p\d+";
$(pattern).addClass(".red");
});
div {
width: 100px;
height: 100px;
margin: 20px;
background: green;
}
.red {background: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="p27"></div>
<div id="p46"></div>
<div id="p124"></div>
最佳答案
当然,您可以使用 filter
应用您需要的任何特定逻辑的方法:
$(function(){
$("div")
.filter(function() { return /^p\d+$/.test(this.id); })
.addClass("red");
});
div {
width: 100px;
height: 100px;
margin: 20px;
background: green;
}
.red {background: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="p27"></div>
<div id="nomatch"></div>
<div id="p124"></div>
关于javascript - 如何使用 jQuery 正则表达式查找具有特定 ID 的所有 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28190428/