我有一个页面,其中包含几个链接,其中包括:
<a href="http://stackoverflow.com">Link</a>
我有以下代码:
$('a').filter(function(){
return this.href == 'http://stackoverflow.com';
}).css('color', 'red');
由于某种原因,过滤器中的函数永远不会返回 true。我做错了什么?
编辑:
$('a').filter(function(){
this.href == 'http://stackoverflow.com';
}).css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://stackoverflow.com">Link</a>
最佳答案
浏览器会自动在 anchor href
的 url
末尾或域名处添加尾部斜杠 /
,因此应该是:
return this.href == 'http://stackoverflow.com/';
希望这有帮助。
看看Is trailing slash automagically added on click of home page URL in browser?
$('a').filter(function(){
return this.href == 'http://stackoverflow.com/';
}).css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://stackoverflow.com">Link</a>
关于jquery - 比较 href 值时无法让 filter() 返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41187862/