2014-09-25 67 views
0

我试图显示和隐藏点击jQuery的一些行?到目前为止,我试图得到一个链接,我点击则ID与一些​​后缀串联然后我尝试切换具有该ID的行,所以我的html和查询代码是这样的:隐藏和显示基于它的id与jquery的特定行

<table> 
    <tr> 
     <td>col_1</td> 
     <td><a href="#" id="1" class="show_row">click me</a></td> 
    </tr> 
    <tr class="hide_row" id="1_preview"> 
     <td>Hiden contet</td> 
     <td><a href="#" id="1" class="hide_row">done</td> 
    </tr> 
    <tr> 
     <td>col_1</td> 
     <td><a href="#" id="2" class="show_row">col_2</a></td> 
    </tr> 
    <tr class="hide_row" id="2_preview"> 
     <td>a</td> 
     <td><a href="#" id="2" class="hide_row">done</td> 
    </tr> 
</table> 

jQuery的:

$(".hide_row").hide(); 

$(".show_row").click(function() { 
    var rowId = $(".show_row").attr('id'); 
    alert(rowId); 
    $('#' + rowId + '_preview').show(); 
}); 
$(".hide_row").click(function() { 
    var rowId = $(this).attr('id'); 
    $('#' + rowId + '_preview').hide(); 
}); 

如何编辑我的jQuery的工作,因为我描述?

+0

我会建议,请不要使用ID =“1”,一次以上。如果你可以使用它作为class =“1”,会更好。也请使用有效的标识符名称。 – maddy 2014-09-25 06:04:58

+0

http://jsfiddle.net/47j47Lud/ – 2014-09-25 06:05:14

回答

0

而不是

var rowId = $(".show_row").attr('id'); 

使用

var rowId = $(this).attr('id'); 

因为里面有DOM元素的另一个用的小变化show_row类 和休息都在里面捣鼓看到here

+0

谢谢。它的工作完美 – 2014-09-25 06:12:15

+0

您的欢迎.. @ LongTran – 2014-09-25 06:12:35

0

您的<tr><a>与相同类别(hide_row)在加载时隐藏。如果a.show_row被点击,您的a.hide_row不会显示,因为它没有与您的tr.hide_row具有相同的ID。为了解决你的问题:

$("tr.hide_row").hide(); 

$(".show_row").click(function() { 
    var rowId = $(this).attr('id'); 
    alert(rowId); 
    $('#' + rowId + '_preview').show(); 
}); 
$("a.hide_row").click(function() { 
    var rowId = $(this).attr('id'); 
    $('#' + rowId + '_preview').hide(); 
});