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

jQuery this.href String Comparison Not Working

本文关键字:比较 不起作用 字符串 href this jQuery      更新时间:2023-09-26

我有一个简单的jQuery脚本,我正在尝试构建它,但我无法让href字符串比较返回true:

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

我的脚本如下:

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

我一直收到"不"的警报,甚至认为 hrefs 是相同的。我错过了什么?

更改:

if ($(this).href

自:

if (this.href

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

要读取属性,您需要使用 attrattribute的简写)

这是你应该拥有的:

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

试试这个:

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

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

请参阅 .attr() 并尝试:

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

相反