我有如下所示的 HTML 片段。我从后端多次生成此片段。当我单击“保存”按钮时,我使用 $(this) 选择器捕获单击了哪个“保存”按钮。现在我想抓取相应保存按钮的属性item-id。我有以下 jquery 代码片段。但这不起作用。我试图查看,但我不知道错误在哪里。
<td><input type="text" size="10" value="val1" item-id="id1"></td>
<td><input type="text" value="val2" size="4"></td>
<td>
<button class="btn btn-primary save-btn">Save</i></button>
</td>
这是 jquery 代码片段
$(".save-btn").click(function(){
var ems = $(this).parent().siblings();
var item_id = ems[0].child().attr("item-id");
}
最佳答案
click
不适用于动态添加的元素。您需要使用 on('click')
。另外,没有方法.child()
,因此您需要使用.children().first()
。
这是更正后的代码:
$(document).on('click', '.save-btn', function(){
var ems = $(this).parent().siblings();
var item_id = ems.children().first().attr("item-id");
});
// The text
var text="";
text += "<td><input type=\"text\" size=\"10\" value=\"val1\" item-id=\"id1\"><\/td>";
text += "<td><input type=\"text\" value=\"val2\" size=\"4\"><\/td> ";
text += "<td>";
text += " <button class=\"btn btn-primary save-btn\">Save<\/i><\/button>";
text += "<\/td>";
// Adding the text to html
$('body').html(text);
$(document).on('click', '.save-btn', function(){
var ems = $(this).parent().siblings();
console.log(ems);
var item_id = ems.children().first().attr("item-id");
alert(item_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于javascript - 如何从元素列表遍历dom树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35857235/