【问题标题】:How do I change an href on first click and go to it on the second click?如何在第一次单击时更改 href 并在第二次单击时转到它?
【发布时间】:2012-11-03 16:34:52
【问题描述】:

我试图在第一次单击时更改列表项的文本和 href。在第二次单击时,它应该转到新的 url。以下是我尝试过的几种方法:

HTML

<ul class="nav">
  <li><a href="#">Click me</a></li>
</ul>

jQuery

这种方式会更改文本,然后立即转到新的 url。

$('ul.nav li:nth-child(1) a[href="#"]').click(function() {
  $(this).text('New Text');
  $(this).attr('href', 'http://www.website.com');
});

第二种方式切换文本和 href,但 preventDefault() 仍然阻止我转到新 URL,尽管在选择器中指定了 a[href="#"]。

$('ul.nav li:nth-child(1) a[href="#"]').click(function(e) {
  $(this).text('New Text');
  e.preventDefault();
  $(this).attr('href', 'http://www.website.com');
});

【问题讨论】:

  • 检查.one()方法here
  • 尽管在选择器中指定了 a[href="#"],但您的语句“preventDefault() 仍然阻止我访问新 URL”并不清楚。请详细说明...
  • 这就是e.preventDefault() 应该做的,防止默认行为——正如inhan 建议的那样,查找.one()
  • 对不起,我刚开始学习 jQuery。我认为指定 a[href="INSERTURL"] 应该只选择具有该特定 url 的 href。我的逻辑是一旦点击它,一旦 url 改变并且不再匹配选择器中的内容,因此不会再次触发。感谢您的意见。
  • @Jeff - 如果您使用.click().on() 的非委托形式,它会将处理程序绑定到当时与您的选择器匹配的所有元素,即使元素稍后会更新,以使它们不再匹配。如果您使用.on() 的委托形式,它将按您的想象工作:$('ul.nav li:nth-child(1)').on('click', 'a[href="#"]', function() {...

标签: jquery onclick href


【解决方案1】:

改用 .one('click') 只绑定一次点击

$('ul.nav li:nth-child(1) a[href="#"]').one('click', function(e) {
  e.preventDefault();
  $(this).text('New Text').attr('href', 'http://www.website.com');
});

【讨论】:

  • +1。出于某种原因,我在写答案时甚至没有想到.one()。不错。
  • @nnnnnn 哈哈,太酷了,你的声望点够多了!是时候分享了;)
  • 太棒了!这正是我一直在寻找的。我不敢相信这很容易。
  • @Jeff 是的,有时我们太忙了以至于忘记了某些事情实际上有一个简单的解决方案!...很高兴这对你有用!
【解决方案2】:

您有多种选择,包括在第一次点击后删除点击处理程序(使用像您使用的非委托事件处理程序只会影响刚刚点击的元素):

$('ul.nav li:nth-child(1) a[href="#"]').click(function(e) {
  $(this).text('New Text')
         .attr('href', 'http://www.website.com')
         .off('click'); // remove click handler
  e.preventDefault();
});

...或设置一个标志,以便您判断它是否已被更改:

$('ul.nav li:nth-child(1) a[href="#"]').click(function(e) {
   var $this = $(this);
   if (!$this.data("urlChanged")) {
      $this.text('New Text')
           .attr('href', 'http://www.website.com')
           .data("urlChanged", true);
      e.preventDefault();
   }
});

【讨论】:

    【解决方案3】:
    $('ul.nav li:nth-child(1) a[href="#"]').click(function(e) {
      var elem = $(this);
      if(!elem.hasClass("changed")){
        elem.addClass("changed");
        $(this).text('New Text');
        $(this).attr('href', 'http://www.website.com');
        e.preventDefault();
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2013-01-06
      • 1970-01-01
      • 1970-01-01
      • 2015-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      相关资源
      最近更新 更多