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

Javascript JQuery:查找具有特定数据属性值的行(索引),javascript,jquery,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_

我正试图在一个表中的特定行后面添加一个字符串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>
找到索引后,我想将我的输出字符串附加到此行

$(want).insertAfter(...?);
还有。。。我注意到每当我这样做

alert( want = $("tr").find("[data-my_other_id='" + my_other_id + "']").length)
我得到0


如果我的问题不够清楚,请帮助我,让我知道,以便我能更好地解释

这是因为find不会搜索兄弟姐妹,只搜索子代。尝试将搜索附加到表

html:


演示:

您不需要使用find方法,因为data属性位于tr本身上。此外,索引的使用也不会起作用。请尝试以下方法

$("tr[data-my_other_id='" + my_other_id + "']").insertAfter(...?);

find
查找后代。
TR
不能是自身的后代

尝试使用
filter()


我假设您希望更新内容而不是附加内容,但它实际上不会改变任何东西。我认为您不想这样使用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);
var$row=$('tr[data-my_other_id=“”+id+”);
//应为中tr的索引
//但这可能不是一个好主意-如果稍后添加标题行会怎么样?
var index=row.index()+1;//如果您想要基于1的索引
$row.find(“td”).text(“我是row#”+索引);

在特定表格中查找,这样会更快,您可以使用此方法

Js:

Html


...
一些文本
一些文本
一些文本

或use.filter(),如$(“tr”).filter(“[data-my_other_id=”等)或$(“[data-my_other_id=”+“]”感谢您的回答。由于某些原因,使用find或filter对我不起作用。@Benoir的回答很好。$(“table”).find(“[data-my other_id=”+“+my other_id+”)返回jQuery.fn.jQuery.init[0].这里的问题:有两个问题..您使用的“find”是tr的后代。您使用的索引也是错误的,它返回一个整数。请参阅下面的我的答案,我将避免使用筛选器,因为它将首先选择所有tr's@Justin,它会成功的anyways@Alexander-如果您执行以下操作,则不会执行($(“tr[data-my_other_id='”+my_other_id+”)]“”@Justin JQuery在内部使用过滤器来解析选择器…查看JQuery源代码…如果调用它或JQuery调用,则差别不大it@charlietfl它必须运行选择器sizzle引擎两次->查看所需内容。谢谢。如何在一秒钟内访问一行(未选中)datatable?这里的问题:谢谢-我认为你不能选择两个答案
var my_other_id = 2;
alert( $("table").find("[data-my_other_id='" + my_other_id + "']").length);​
$("tr[data-my_other_id='" + my_other_id + "']").insertAfter(...?);
$("tr").filter("[data-my_other_id='" + my_other_id + "']").index();
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);
$('any-button').click(function(){
    var id = 23;
    var $row = $('.your-class tbody tr[data-id="' + id + '"]');
    $row.remove();
});
<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>