javascript jQuery this.href 字符串比较不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11298953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:40:55  来源:igfitidea点击:

jQuery this.href String Comparison Not Working

javascriptjquerythishref

提问by Kyle Suss

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:

我有一个简单的 jQuery 脚本,我正在尝试构建它,但我无法让 href 字符串比较返回 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?

我一直收到“不”的警报,即使认为 href 是相同的。我错过了什么?

回答by Blaster

Change:

改变:

if ($(this).href

To:

到:

if (this.href

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

或者,$(this).attr('href')但前者更好。

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

要读取属性,您需要使用attr(简写为attribute

This is what you should have:

这是你应该拥有的:

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

回答by undefined

try this:

试试这个:

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

回答by Paul

jQuery objects don't have an hrefproperty. Just access the property of the HTMLAnchorElementusing this.hrefinstead of creating a new jQuery object with $(this).

jQuery 对象没有href属性。只需访问该财产HTMLAnchorElement使用this.href,而不是创建一个新的jQuery对象$(this)

回答by Fydo

See .attr()and try this:

参见.attr()并试试这个:

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

instead

反而