2017-07-07 65 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任何表格图像的工作。