2017-07-07 64 views
0

如何使用jQuery將類添加到下一張圖片?Jquery將類添加到下一張圖片​​使用JQuery標記

我已使用循環的網頁圖像。它們顯示在表格行中。

<table class="table table-bordered"> 
    <?php 
    <td><img class="img1" src="http://s5.tinypic.com/30v0ncn_th.jpg"/></td> 

    for ($x = 0; $x < 5; $x++) { ?> 
     <td> 
     <img class="loopimg" src="http://s5.tinypic.com/30v0ncn_th.jpg"/> 
     </td> 
    <?php } ?> 
</table> 

我想什麼實現的是當我第一次圖像(類=「IMG1」)上單擊,將其添加類下一個圖像,點擊,將添加類下一個圖像。

$('.img1').click(function(){ 
    $(this).parent().next("td").addClass("active"); 
    alert("class"); 
}); 

這個jQuery代碼添加「活性」級到下<td>標籤,我想類被添加到下一個圖像。預先感謝您

+1

[jQuery的學習中心(https://開頭學習.jquery.com) – Andreas

+1

你有一個錯位的<?php'標籤。它應該在'​​

回答

2

,而你的下一個標籤是TD和你想添加類到它的孩子像你必須使用jQuery庫的兒童功能這樣

$(document).ready(function(){  
      $('.img1').click(function(){ 

     $(this).parent().next("td").children("img").addClass("active"); 

     alert("class"); 
     }); 
     }); 
1

首先請注意,您的HTML無效,因爲您需要有一個<tr>包裝所有<td>

解決您的問題,您可以通過點擊img元素得到父tr,然後找到內的第一.loopimg元素,像這樣:

$('.img1').click(function(){ 
    $(this).closest('tr').find('.loopimg:first').addClass("active"); 
}); 

也有你的PHP語法的一些重大問題 - 但是我會假設這些只是由你將代碼轉換成問題引起的,因爲在當前狀態下它根本不起作用。

1

添加類TD孩子:

$('.table .img').click(function(){ 
    $(this).parent().next("td").children('img').addClass("active"); 
    alert("class"); 
}); 

我改變選擇到。表.IMG任何表格圖像的工作。