jQuery this.href String Comparison Not Working

只谈情不闲聊 提交于 2019-12-12 01:00:21

问题


I have a simple jQuery script that I'm trying to build upon but I can't get the href string comparison to return true:

<a class="test" href="/Services/Cloud-Hosting">Click Me</a>​

My script is as follows:

$('.test').click(function() {
if ($(this).href == "/Services/Cloud-Hosting") {
    alert('hi');
}
else {
    alert('no');
}
});​

I keep getting the alert of 'no' even thought the hrefs are the same. What am I missing?


回答1:


Change:

if ($(this).href

To:

if (this.href

Or $(this).attr('href') but former is better.

To read attributes, you need to use attr (shorthand for attribute)

This is what you should have:

if (this.href == "/Services/Cloud-Hosting") {
    alert('hi');
}
else {
    alert('no');
}



回答2:


try this:

if ($(this).attr('href') == "/Services/Cloud-Hosting") {



回答3:


jQuery objects don't have an href property. Just access the property of the HTMLAnchorElement using this.href instead of creating a new jQuery object with $(this).




回答4:


See .attr() and try this:

$(this).attr('href') == "/Services/Cloud-Hosting"

instead



来源:https://stackoverflow.com/questions/11298953/jquery-this-href-string-comparison-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!