1

我有一个简单的 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是相同的,我也会不断收到“不”的警报。我错过了什么?

4

4 回答 4

10

改变:

if ($(this).href

到:

if (this.href

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

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

这是你应该拥有的:

if (this.href == "/Services/Cloud-Hosting") {
    alert('hi');
}
else {
    alert('no');
}
于 2012-07-02T18:14:51.283 回答
4

试试这个:

if ($(this).attr('href') == "/Services/Cloud-Hosting") {
于 2012-07-02T18:15:43.880 回答
1

请参阅.attr()并尝试以下操作:

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

反而

于 2012-07-02T18:15:28.383 回答
1

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

于 2012-07-02T18:18:26.777 回答