[英]JQuery: Find (the index of) a row with a specific data attribute value
我試圖在類似於這一個的表中的特定行之后追加一個字符串myoutput:
<table>
<tr data-my_id='1'> <td> content </td> </tr>
<tr data-my_id='2' data-my_other_id='1' > <td> content </td> </tr>
<tr data-my_id='3' data-my_other_id='2' > <td> content </td> </tr>
</table>
所以,假設我想在tr之后將輸出字符串附加到data-my_other_id='2'
(請注意,在我的代碼中, my_other_id = 2
已經存在)
我試圖這樣做:
var want = $("tr").find("[data-my_other_id='" + my_other_id + "']").index();
找到索引后,我想將輸出strhing追加到這一行......
$(want).insertAfter(...?);
還有...我什么時候都注意到了
alert( want = $("tr").find("[data-my_other_id='" + my_other_id + "']").length)
我得到0 ......
請幫助我,如果我的問題不夠明確,請告訴我,以便我能更好地解釋。
我假設你想要更新內容而不是追加,但它並沒有真正改變任何東西。 我不認為你想以這種方式使用find()。 嘗試類似的東西:
var $row = $('tr[data-my_other_id="' + id + '"]');
// should be the index of the tr in the <table>
// this may not be a good idea though - what if you add a header row later?
var index = row.index() + 1; // if you want 1-based indices
$row.find("td").text("I am row #" + index);
這是因為find不會搜索兄弟姐妹,只會搜索孩子。 嘗試將搜索附加到表格。
HTML:
<table>
<tr data-my_id='1'> <td> content </td> </tr>
<tr data-my_id='2' data-my_other_id='1' > <td> content </td> </tr>
<tr data-my_id='3' data-my_other_id='2' > <td> content </td> </tr>
</table>
JS:
var my_other_id = 2;
alert( $("table").find("[data-my_other_id='" + my_other_id + "']").length);
演示: http : //jsfiddle.net/gDb3A/
您不需要使用find方法,因為數據屬性在tr本身上。 你使用索引也行不通。 請嘗試以下方法。
$("tr[data-my_other_id='" + my_other_id + "']").insertAfter(...?);
find
后代。 TR
不能成為它自己的后代。
嘗試使用filter()
$("tr").filter("[data-my_other_id='" + my_other_id + "']").index();
在特定的表中查找它會更快,您可以使用此方法。
JS:
$('any-button').click(function(){
var id = 23;
var $row = $('.your-class tbody tr[data-id="' + id + '"]');
$row.remove();
});
HTML
<table class="table table-striped your-class">
<thead>
<tr>...<tr/>
</thead>
<tbody>
<tr data-id="23">Some text</tr>
<tr data-id="43">Some text</tr>
<tr data-id="43">Some text</tr>
</tbody>
</table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.