2011-06-16 58 views
1

我很难弄明白这一点,所以也许有人可以帮助我。jQuery禁用锚标记并选择子元素?

这是我的html:

<p> 
post content 
<span><a href="#" class="voteUp">I approve this message <span>${post.upvotes}</span></a></span> 
</p> 

<p> 
post #2 content 
<span><a href="#" class="voteUp">I approve this message <span>${post.upvotes}</span></a></span> 
</p> 

而我的JS:

$(".voteUp").click(function(){ 
    $.post(voteAction({postid: this.id, type: 'up'}), function(data){ 
     $("a span").html(data); 
    }); 
}); 

基本上就是我想要做的是与data包含的值更改内部跨度的价值。上面的代码确实有效,但它正在改变每个跨度的内容,而不仅仅是被点击的锚点的孩子。

我想要做的另一件事是在投票提交后禁用锚标记。

任何想法如何做到这一点?

回答

2

尝试:

$(".voteUp").click(function(){ 
    var voteUp = $(this); 
    if(voteUp.hasClass('disabled'){ 
     // don't do anything, because it's disabled 
    } else{ 
     $.post(voteAction({postid: this.id, type: 'up'}), function(data){ 
      voteUp 
       .addClass('disabled') // add a class, which you can check on a click event fired 
       .find("span") 
       .html(data); 
     }); 
    } 
}); 
+0

没想到用CSS这样做的。谢谢你的帮助! – networkprofile 2011-06-16 22:22:28

+0

@Sled:是的,在这种情况下,元素的类可以用于样式和逻辑。 – Shef 2011-06-16 22:27:15

0

尝试

$(document).ready(function() { 

    $(".voteUp").click(function() { 

     $.post(voteAction({postid: this.id, type: 'up'}), function(data) { 

      $(this).children("span").html(data); 

     }); 

     $(this).unbind('click'); 
    }); 
}); 
1

请记住,从$。员额回调函数是异步的,所以你失去了你的情况下没有适当的框架。所以,这意味着你的$('a span')搜索整个DOM,因此它为什么要取代所有的东西。

编辑:好吧,SHEF是鸡蛋里挑骨头,但让我意识到,使用解除绑定(或SHEF的方法)仍不会在点击返回false,因此将有一个很好的“踢顶端”的效果,当你点击<a href="#">。此代码已更新以解决该问题。现在

$("a.voteUp").click(function(){ 
    //Set a local variable to the anchor that was clicked on for future use 
    var $this = $(this); 
    $.post(voteAction({postid: this.id, type: 'up'}), function(data){ 
     $this.find("span").html(data); 

     //Unbind this "voteUp" button. This will remove the click handler and apply a class of "disabled" 
     $this.unbind('click').click(function() { return false }).addClass('disabled'); 
    }); 
    return false; 
}); 

,在你的CSS:

.disabled { color: #999; } 

这将使中的元素是 “禁用” 的文字是灰色的。

+1

这只会''解除'a'标签上的点击事件,但'a'标签本身仍然是可点击的。 – Shef 2011-06-16 22:13:14

+0

这是正确的。点击它将无所作为,这是我解释他的问题的方式。如果他想让它什么都不做并灰掉,那么他可以添加这条线来做到这一点。 – 2011-06-16 22:16:02

+0

感谢您的帮助!禁用链接不起作用,但是这部分'$ this.find(“span”)。html(data);'虽然没有找到内部的'a'(就像Goblin所建议的那样)。任何想法关于禁用链接? – networkprofile 2011-06-16 22:17:33

1

试试这个:

$(".voteUp").click(function(){ 
    $.post(voteAction({postid: this.id, type: 'up'}), function(data){ 
     // Replace <span> that's a child of this: 
     $('span', this).html(data); 
     // Unbind click event from anchor: 
     $(this).unbind('click'); 
    }); 
}); 

如果你想删除的,而不是解除绑定click事件的锚标记,这样做:

$(this).parent().html($(this).html());

+0

我应该注意,以上述方式移除标签将替换父元素的全部内容,因此请务必将包装在中。 – Goblin 2011-06-16 22:21:26