在jQuery中,可以使用属性选择器来选择具有特定类名的元素。当需要选择类名以特定字符串开头的元素时,可以使用属性选择器的"^="形式。
要选择所有类名以"text-"开头的元素,可以使用以下jQuery选择器:
$('[class^="text-"]')
或者更精确的版本(只匹配类名以"text-"开头,而不是类属性以"text-"开头):
$('[class*=" text-"], [class^="text-"]')
[class^="text-"]
- 选择class属性值以"text-"开头的元素<div class="text-red">
但不匹配<div class="other text-red">
[class*=" text-"]
- 选择class属性值中包含" text-"的元素(注意前面的空格)<div class="other text-red">
但不匹配<div class="text-red">
<!DOCTYPE html>
<html>
<head>
<title>jQuery Class Starts With Selector</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.text-red { color: red; }
.text-blue { color: blue; }
.text-green { color: green; }
.other-text { font-weight: bold; }
</style>
</head>
<body>
<p class="text-red">红色文本</p>
<p class="text-blue">蓝色文本</p>
<p class="other-text text-green">绿色加粗文本</p>
<p class="other">普通文本</p>
<script>
$(document).ready(function() {
// 选择所有类名以"text-"开头的元素并添加边框
$('[class*=" text-"], [class^="text-"]').css('border', '1px solid black');
// 也可以这样写
// $('[class^="text-"], [class*=" text-"]').css('border', '1px solid black');
});
</script>
</body>
</html>
如果只需要选择具有特定类名前缀的元素,也可以使用jQuery的filter方法:
$('*').filter(function() {
return this.className.split(/\s+/).some(function(cls) {
return cls.indexOf('text-') === 0;
});
});
这种方法更精确但性能较差,适合在复杂选择场景中使用。
没有搜到相关的文章