2014-09-10 42 views
-4

由於某些原因,下面的代碼只會觸發彈出框中選定的第一個刪除按鈕。所有其他按鈕什麼也不做。我怎樣才能修改它,以便這個按鈕調用腳本,而不管它被點擊的是哪一行。jquery點擊監聽器只在表格的第一行工作

<a class="btn btn-danger" id="delete">Delete</a> 

這是我html

@foreach(Tweet::orderBy('created_at', 'DESC')->get() as $tweet) 
        <tr id="{{$tweet->tweet_id}}"> 
         <td><a class="btn btn-danger" id="delete">Delete</a></td> 
         <td id="tweet_text">{{$tweet->tweet_text}}</td> 
         <td id="tweet_user">{{$tweet->screen_name}}</td> 
         <td>{{$tweet->name}}</td> 
         <td id="tweet_date">{{$tweet->created_at}}</td> 
        </tr> 
@endforeach 

這是我的 'script'

<script> 
    //When the delete button is clicked open the pop up. 
    $('#delete').click(function(){ 
     $('#myModal').modal({show:true}); 
     //Get the clicked row 
     var row = $(this).closest('tr'); 
     //Get the ID of the Tweet - the row id 
     var tid = row.attr('id'); 
     //Get the tweet, user and date 
     var tweet = row.find('#tweet_text'); 
     var user = row.find('#tweet_user'); 
     var date = row.find('#tweet_date'); 
     //Display details in the pop up 
     $('.modal_tweet_text').text(tweet.text()); 
     $('.modal_tweet_user').text(user.text()); 
     $('.modal_tweet_date').text(date.text()); 
     $('.modal_tweet_id').text("Tweet ID: " + tid); 
     //Confirm Action 
     $('#confirm_btn').click(function(){ 
      row.remove();//remove the row 
      $('#myModal').modal('hide');//Hide the popup 
     }); 
    }); 
</script> 
+7

__IDs必須unique__ – Satpal 2014-09-10 12:34:01

+0

不要以爲這是公平的,這個問題被壓低了,我提供了所有的信息,並且有大量的代碼。 – Javacadabra 2014-09-10 12:51:27

回答

7

不能使用多個按鈕同一ID,因此,使用類選擇將其更改爲類

<a class="btn btn-danger delete">Delete</a> 

和綁定click事件

$('a.delete').click(function(){ 
     $('#myModal').modal({show:true}); 
     //Get the clicked row 
     var row = $(this).closest('tr'); 
     //Get the ID of the Tweet - the row id 
     var tid = row.attr('id'); 
     //Get the tweet, user and date 
     var tweet = row.find('#tweet_text'); 
     var user = row.find('#tweet_user'); 
     var date = row.find('#tweet_date'); 
     //Display details in the pop up 
     $('.modal_tweet_text').text(tweet.text()); 
     $('.modal_tweet_user').text(user.text()); 
     $('.modal_tweet_date').text(date.text()); 
     $('.modal_tweet_id').text("Tweet ID: " + tid); 
     //Confirm Action 
     $('#confirm_btn').click(function(){ 
      row.remove();//remove the row 
      $('#myModal').modal('hide');//Hide the popup 
     }); 
    }); 
1

使用事件代表團,按鈕不再出現,一旦你刪除它。

$(document).on('click','#delete',function(){ 
相關問題