【问题标题】:jQuery this.href String Comparison Not WorkingjQuery this.href 字符串比较不起作用
【发布时间】:2012-07-03 04:17:48
【问题描述】:

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

【问题讨论】:

标签: javascript jquery this href


【解决方案1】:

变化:

if ($(this).href

收件人:

if (this.href

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

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

这是你应该拥有的:

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

【讨论】:

  • 小心使用this.href,在Chrome中它返回链接的绝对路径(不管href是一个相对URL)。 Demo.
  • @DavidsaysreinstateMonica 该提示非常有价值,我认为值得在该指南中发布一个新答案,以便研究人员更容易理解其中的差异。
【解决方案2】:

试试这个:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 正如另一个答案this.href 不一定等于$(this).attr('href')Demo.
    • @DavidThomas 在那种情况下this.getAttribute('href') 不是首选方式吗?
    【解决方案4】:

    查看.attr() 并试试这个:

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

    改为

    【讨论】:

      猜你喜欢
      • 2011-09-20
      • 2014-04-03
      • 2012-01-22
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多