javascript - 如何为 X 个元素关联点击功能?

标签 javascript jquery html css

如果我有一个包含数百行的表,我可以为每一行和每个组件分配一个 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());
});

DEMO

关于javascript - 如何为 X 个元素关联点击功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21764922/

相关文章:

html - 实现 CSS : Always show side-nav even on mobile?

html - 自动拉伸(stretch)垂直列 (divs)

javascript - 我有一个基于计数器的 if/else 语句,但由于某种原因,else 不起作用

javascript - Cypress :如何在我的前端 react 应用程序和不受我控制的第 3 方 API(服务器)之间执行测试?

javascript - 以正确的格式将数据保存到 JSON 文件 - PHP

Javascript 全局变量在 jQuery Droppable 中不起作用

java - 如何在 Swing 中将 html 显示为树?

javascript - React-Native map 数据并保存所有项目

jquery - 如何使用 html 控件(如标签)附加 Html5 选择(下拉列表)

jQuery 数据表 : how to delete the row