如果我有一个包含数百行的表,我可以为每一行和每个组件分配一个 id(因为该表是动态创建的)。
但是如果例如在每一行中,我都有一个复选框,我想将每个复选框与单击时的一个函数相关联,以在同一行的另一列中执行某些操作,我该怎么做?
我是否必须为每个复选框定义一个 onclick 方法?我如何访问同一行的另一列?
更新:
我尝试了这个建议,但它不起作用。示例:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<table id="main_table" border="1">
<tr><th>First</th><th>Last</th><th>Modify</th></tr>
<tr>
<td>Jim</td><td><input id="rep1" type="text" disabled value="X"></td><td><input class=".checkbox" type="checkbox"> </td>
</tr>
</table>
</body>
<script type="text/javascript">
$(document).delegate('change', "#main_table :checkbox", function(){
console.log("In function");
if(this.checked){ //If you want to perform checked check
alert("Hello");
}
});
</script>
</html>
更新 2:
以下也不起作用:
$("#main_table ").delegate('click', ":checkbox", function(){
console.log("In function");
if(this.checked){ //If you want to perform checked check
alert(parentTd);
}
});
更新 3:
以下也适用:
$("#main_table ").on('click', ":checkbox", function(){
console.log("In function");
if(this.checked){ //If you want to perform checked check
alert(parentTd);
}
});
delegate
似乎不起作用?任何人都可以向我解释我搞砸了什么吗?
最佳答案
您可以为所有这些分配一个处理程序。在处理程序中,$(this)
是被点击触发处理程序的元素,然后您可以使用 DOM 遍历方法找到与其相关的其他元素,例如
$("#yourtable").on("click", ".checkbox", function() {
$(this).closest("tr").find(".destination").text("Clicked on checkbox in this row");
});
此示例假设每行中有一个带有 class="checkbox"
的复选框,以及另一个带有 class="destination"
的字段。
更新:使用您的 HTML:
$("#main_table").on("click", ".checkbox", function () {
alert($(this).closest("tr").find("input[type=text]").val());
});
关于javascript - 如何为 X 个元素关联点击功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21764922/