在jQuery中,属性选择器包装在方括号[]中。 这是受支持的属性选择器:
1.具有属性[A]
选择所有具有“ A”属性的元素。
例子
$('a [rel]')–选择与<a>匹配的所有具有rel属性的元素。
2.属性值等于[A = B]
选择所有具有A属性的值完全等于B的元素。
例子
$('a [rel = nofollow]')–选择所有与<a>匹配的,具有rel属性且值等于'nofollow'的元素。
3.属性值不等于[A!= B]
选择所有不具有A属性的值完全等于B的元素。
例子
$('a [rel!= nofollow]')–选择与<a>匹配的所有不具有rel属性且其值完全等于'nofollow'的元素。
4.属性值开始[A ^ = B]
选择所有具有A属性且其值以B开头的元素。
例子
$('a [rel ^ = nof]')–选择与<a>匹配且具有rel属性且其值以'nof'开头的所有元素。
5.属性值结尾[A $ = B]
选择所有具有A属性且其值以B结尾的元素。
例子
$('a [rel $ = low]')–选择与<a>匹配且具有rel属性且值以'low'结尾的所有元素。
6.属性值包含[A * = B]
选择所有具有A属性且其值包含子字符串B的元素。
例子
$('a [href * = yahoo.com]')–选择与<a>匹配且具有href属性且值包含'yahoo.com'的所有元素。
7.属性值包含前缀[A | = B]
选择所有具有A属性的值等于B或以B开头且后跟连字符(-)的元素。
例子
$('a [lang | = en]')–选择与<a>匹配的所有具有lang属性,其值等于'en'或'en-'的元素。
8.属性值包含–用空格分隔[A〜= B]
选择所有具有A属性且其值等于B并以空格分隔的元素。
例子
$('div [class〜= jQuery]')–选择所有与<div>匹配的元素,这些元素具有class属性,其值等于'jQuery',以空格分隔。 例如,“ Hello jQuery”将匹配,“ Hello-jQuery”和“ HellojQuery”将不匹配。
播放
单击按钮在属性选择器周围播放。
<html>
<head>
<title>jQuery attribute selector example</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<style type="text/css">
div, a{
padding:16px;
}
#msg{
padding:8px;
hright:100px;
}
</style>
</head>
<body>
<h1>jQuery attribute selector example</h1>
<div id="msg"></div>
<div>
<a rel="nofollow" href="http://www.google.com" lang="en-US">
Google - <a rel="nofollow" href="http://www.google.com" lang="en-US">
</a>
</div>
<div>
<a href="http://www.yahoo.com" lang="en">
Yahoo - <a href="http://www.yahoo.com" lang="en" >
</a>
</div>
<div>
<a href="http://www.abc-yahoo.com" lang="-en">
Yahoo - <a href="http://www.abc-yahoo.com" lang="-en">
</a>
</div>
<div class="Hello-jQuery">
class = "Hello-jQuery"
</div>
<div class="Hello jQuery">
class = "Hello jQuery"
</div>
<div class="HellojQuery">
class = "HellojQuery"
</div>
<br/><br/>
<button>a[rel]</button>
<button>a[rel=nofollow]</button>
<button>a[rel!=nofollow]</button>
<button>a[rel^=nof]</button>
<button>a[rel$=low]</button>
<button>a[href*=yahoo.com]</button>
<button>a[lang|=en]</button>
<button>div[class~=jQuery]</button>
<button id="reset">Reset It</button>
<script type="text/javascript">
$("button").click(function () {
var str = $(this).text();
$('a').css("border", "0px solid #000000");
$(str).css("border", "1px solid #ff0000");
$('#msg').html("<h2>Attribute Selector : " + str + "</h2>");
});
$("#reset").click(function () {
location.reload();
});
</script>
</body>
</html>
翻译自: https://mkyong.com/jquery/jquery-attribute-selector-examples/