Jquery 如何在第一次单击时更改href并在第二次单击时转到它?

Jquery 如何在第一次单击时更改href并在第二次单击时转到它?,jquery,onclick,href,Jquery,Onclick,Href,我试图在第一次单击时更改列表项的文本和href。在第二次单击时,它应该转到新的url。以下是我尝试过的几种方法: HTML <ul class="nav"> <li><a href="#">Click me</a></li> </ul> 第二种方式是切换text和href,但是preventDefault()仍然阻止我访问新的URL,尽管在选择器中指定了[href=“#”] $('ul.nav li:nth-child

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

HTML

<ul class="nav">
  <li><a href="#">Click me</a></li>
</ul>
第二种方式是切换text和href,但是preventDefault()仍然阻止我访问新的URL,尽管在选择器中指定了[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('click')只绑定一次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');
});

您有几个选项,包括在第一次单击后删除单击处理程序(使用像您正在使用的那样只会影响刚刚单击的元素的非委托事件处理程序):

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

$('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();
   }
});

检查
.one()
方法。您的语句“preventDefault()仍然阻止我访问新URL,尽管在选择器中指定了[href=“#”]”不清楚。请详细说明……这就是
e.preventDefault()
应该做的,防止默认行为——正如inhan建议的,查找
.one()
对不起,我刚开始学习jQuery。我认为指定[href=“INSERTURL”]应该只选择具有该特定url的href。我的逻辑是,一旦点击它,url就会改变,不再匹配选择器中的内容,因此不会再次触发。谢谢您的输入。@Jeff-如果您使用
.click()
.on()
的非委托形式,它会将处理程序绑定到当时与您的选择器匹配的所有元素,并且即使这些元素后来更新到不再匹配,这些处理程序也会保留。如果你使用
.on()
的委托形式,它会像你想象的那样工作:
$('ul.nav li:nth child(1)')。on('click','a[href=“#”]”,function(){…
+1。出于某种原因,我在写我的答案时甚至没有想到
.one()
。很好。@nnnnnnnn哈哈,很酷,你得到了足够的声誉积分!时间分享;)太棒了!这正是我想要的。我真不敢相信这么容易。@Jeff是的,有时候我们太专注了,以至于忘记了有些事情其实有一个简单的解决方案!…很高兴这对你有用!
$('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();
   }
});
$('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();
  }
});