如何解决jQuery:属性选择器无法正常工作
| 给定下面的代码,我希望有一个警报“ \“ searchRes1 \”,它是id的直接匹配项,对于第二个块,由于id包含\,我希望它也能警报其他两个div \ “搜索\”。我想念什么? <div id=\"sRes\">
<h4>Search for things</h4>
<div id=\"searchRes1\">123</div>
<div id=\"searchRes2\">456</div>
<div id=\"searchRes3\">789</div>
</div>
<script>
$(\"#sRes div[id=\'searchRes1\']\").each(function () {
alert($(this).attr(\"id\"));
});
$(\"#sRes div[id~=\'search\']\").each(function() {
alert($(this).attr(\"id\"));
});
</script>
解决方法
在CSS选择器中,contains(
~=
)表示包含完整单词。这对于诸如rel=\"foo bar\"
之类的东西可能会有用,而by3ѭ,rel~=\'bar\'
却不匹配rel~=\'fo\'
。
尝试使用startsWith(^=
):
$(\"#sRes div[id^=\'search\']\")
http://www.w3.org/TR/css3-selectors/#attribute-selectors
,第一个对我来说工作正常http://jsfiddle.net/raW26/
对于第二个可行的方法,我认为您选择的属性必须由空格分隔
您必须使用*=
或^=
才能正常工作
附言您不需要使用$(this).attr(\"id\")
只需this.id
就足够了
$(\"#sRes div[id=\'searchRes1\']\").each(function () {
alert($(this).attr(\"id\"));
});
$(\"#sRes div[id*=\'search\']\").each(function() {
alert($(this).attr(\"id\"));
});
,你想念名字,也用!
而不是~
$(\"#sRes div[id!=\'searchRes1\']\").each(function() {
alert($(this).attr(\"id\"));
});
演示
参考
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。