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

Kyl*_*uss 0 javascript jquery this href

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

<a class="test" href="/Services/Cloud-Hosting">Click Me</a>?
Run Code Online (Sandbox Code Playgroud)

我的脚本如下:

$('.test').click(function() {
if ($(this).href == "/Services/Cloud-Hosting") {
    alert('hi');
}
else {
    alert('no');
}
});?
Run Code Online (Sandbox Code Playgroud)

即使href是相同的,我仍然会收到'不'的警报.我错过了什么?

Bla*_*ter 9

更改:

if ($(this).href
Run Code Online (Sandbox Code Playgroud)

至:

if (this.href
Run Code Online (Sandbox Code Playgroud)

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

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

这是你应该拥有的:

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

  • 小心使用`this.href`,在Chrome中它返回链接的绝对路径(无论`href`是相对URL).[演示](http://jsfiddle.net/QCx6D/). (4认同)