JQuery:查找具有特定数据属性值的行(的索引)

mur*_*elg 9 javascript jquery

我试图在类似于这一个的表中的特定行之后追加一个字符串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>
Run Code Online (Sandbox Code Playgroud)

所以,假设我想在tr之后追加我的输出字符串data-my_other_id='2' (请注意,在我的代码中,my_other_id = 2已经存在)

我试图这样做:

var want = $("tr").find("[data-my_other_id='" + my_other_id + "']").index();
Run Code Online (Sandbox Code Playgroud)

找到索引后,我想将输出strhing追加到这一行......

$(want).insertAfter(...?);
Run Code Online (Sandbox Code Playgroud)

还有...我什么时候都注意到了

alert( want = $("tr").find("[data-my_other_id='" + my_other_id + "']").length)
Run Code Online (Sandbox Code Playgroud)

我得到0 ......

请帮助我,如果我的问题不够明确,请告诉我,以便我能更好地解释.

joh*_*ley 15

我假设你想要更新内容而不是追加,但它并没有真正改变任何东西.我不认为你想以这种方式使用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);
Run Code Online (Sandbox Code Playgroud)