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

JQuery: Find (the index of) a row with a specific data attribute value

本文关键字:索引 数据属性 查找 JQuery      更新时间:2023-09-26

我试图在类似于下面的表中的特定行之后附加一个字符串,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();

找到索引后,我想将我的输出字符串附加到这一行…

$(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方法,因为data属性在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>