2012-09-29 44 views
0

我有附連到BTN-組這樣一個jquery函數:只有第一個按鈕被反應以點擊事件

<div class="row"> 
    <!-- Vote button row --> 
    <div class="span8" id="votenumbers"> 
     <div class="btn-group"> 
      <button class="btn" id="votebutton" data-votevalue="1">1</button> 
      <button class="btn" id="votebutton" data-votevalue="2">2</button> 
      <button class="btn" id="votebutton" data-votevalue="3">3</button> 
      <button class="btn" id="votebutton" data-votevalue="4">4</button> 
      <button class="btn" id="votebutton" data-votevalue="5">5</button> 
      <button class="btn" id="votebutton" data-votevalue="6">6</button> 
      <button class="btn" id="votebutton" data-votevalue="7">7</button> 
      <button class="btn" id="votebutton" data-votevalue="8">8</button> 
      <button class="btn" id="votebutton" data-votevalue="9">9</button> 
      <button class="btn" id="votebutton" data-votevalue="10">10</button> 
     </div> 
    </div> 
</div> 

<!-- Vote button row ends --> 

,這是使用分配給各按鈕的功能的JavaScript IM。

$('#votebutton').each(function(){ 
    $(this).click(function(){ 
     var votevalue = $(this).data('votevalue'); 
     var filename = $('.mainimage').data('filename'); 
     var category = $('.mainimage').data('category'); 
      $.ajax({ 
       type: 'POST', 
       url: '?category=' + category, 
       data: { 
        "votevalue" : votevalue, 
        "filename" : filename 
       }, 
       success: function(data){ 
        $('body').html(data); 
       } 
     }); // end ajax 
    }); // end click 
}); // end each 

現在我的問題是,只有第一個按鈕反應click事件。其他則不。不知道爲什麼。

回答

2

您爲'id'屬性賦予了所有按鈕相同的值。在整個HTML頁面中,Id屬性應該是唯一的。您使用的選擇器,$('#votebutton'),一個id選擇器,返回單個元素。這就是爲什麼點擊處理程序只能執行其中一個按鈕。你應該爲每個按鈕分配一個不同的id值,或者根本沒有id。

你可以擺脫身份證上的按鈕乾脆屬性和使用類選擇,而不是,找到按鈕:

$('#votenumbers .btn').each(function() { $(this).click(...) ... }); 
+0

謝謝。學到了新東西。 – user1683645