JQuery:查找具有特定数据属性值的行(索引)
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();
找到索引后,我想将我的输出字符串附加到这一行…
$(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>
相关文章:
- 序列化数据属性中对象的最可靠方法
- jQuery最近父级的数据属性选择器
- delete在Object上效率低下,但在DOM Element's的数据属性,与null out相比
- 数据属性仅在切换设备模式下工作
- 函数jquery.html()不提供数据属性集值
- 在数据属性上进行下拉自动选择
- JavaScript-获取数据属性的值返回未定义的值
- 如何替换数据属性中的特定字符串单词
- 使用数据属性将HTML数据复制到另一个元素
- 带有CSS的数据属性就没那么有用了
- 查找所有TD标签并读取其数据属性
- 使用jQuery获取第N个元素的数据属性值
- 使用自定义数据属性或将数据绑定到处理程序来处理事件
- 数据属性有没有更干净的方法
- 是否可以使用CSS分配数据属性
- 根据jquery数据属性值进行查询
- 使用jQuery在select选项上设置HTML数据属性
- 无法从循环数据属性的内容中获取索引的值
- 按索引或数据属性类
- JQuery:查找具有特定数据属性值的行(索引)