2011-06-16 42 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