2014-09-25 40 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(); 
});