javascript - 使用 jQuery 向许多动态生成的按钮添加事件处理程序
问题描述
我有一个动态生成的表单,其中包含代表公司类别的复选框组。这些最终被绘制在动态图表上(此处未显示)。每组公司都有一个切换按钮,用于打开或关闭每个类别中的所有复选框。
我有一个使用其 ID 的第一个切换按钮(Tech Giants)的 jQuery 处理程序,然后相应地选中或取消选中该组中的所有框。
我的问题是这个,它指的是下面块中的最后一部分代码。与其为每个切换按钮手动编写处理程序,我如何创建一个将应用于页面上所有按钮的处理程序?每个按钮只应选中或取消选中其特定类别中的所有框。请注意,页面上的第一个按钮是独立的,不是我们要处理的类别选择复选框的一部分。
这是 JSFiddle 中的代码: https ://jsfiddle.net/gq5tw309/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This button is different than the other buttons -->
<button class="button-text" id="customize-button">Open User Settings</button>
<!-- Placeholder for dynamic form -->
<div id="company-selection-form"></div>
<script type="text/javascript">
function toMachineString(humanString) {
var machineString = humanString.replace(/\s+/g, '-').toLowerCase();
machineString = machineString.replace('&','');
return machineString;
}
// Setup the form
var categories = new Map([
['Tech Giants',['Alphabet','Amazon','Apple','Facebook','Microsoft']],
['Semiconductors', ['AMD','Intel','Nvidia']],
['Telecoms',['AT&T','Verizon','Sprint','T-Mobile']]
// ...
]);
// Build company selection form inputs
let companySelectionHTML = '';
for (let category of categories) {
categoryName = category[0];
categoryList = category[1];
// Setup a div to differentiate each category of companies.
// Will be used for turning on/off categories en masse
companySelectionHTML += `<div id="${toMachineString(categoryName)}">\n`;
// Category heading
companySelectionHTML += `<h4>${categoryName}</h4><button id="btn-${toMachineString(categoryName)}" data-checked="true">Toggle</button>`;
categoryList.forEach(companyName => {
companySelectionHTML += `
<label class="checkbox-label">
<input id="x-${toMachineString(companyName)}" class="checkbox" type="checkbox" name="company" value="${companyName}" checked>
<label for="x-${toMachineString(companyName)}">${companyName}</label>
</label>`;
});
companySelectionHTML += '</div>\n</div>\n</div>\n';
}
// Append to DOM
const companySelectionId = document.getElementById('company-selection-form');
companySelectionId.insertAdjacentHTML('beforeend', companySelectionHTML);
// Arm the toggle button
// HOW DO I APPLY THIS TO ALL THE TOGGLE BUTTONS INSTEAD OF JUST ONE?
$(document).ready(function(){
$('#tech-giants').click(function() {
// Access the data object of the button
var buttonData = $(this).data();
// Set all checkboxes 'checked' property
$('#tech-giants input[type=checkbox]').prop('checked', !buttonData.checked);
// Set the new 'checked' opposite value to the button's data object
buttonData.checked = !buttonData.checked;
// Update the chart -- code goes here
// dynamically-refresh-chart();
});
});
</script>
谢谢!
解决方案
首先为动态生成的 HTML(按钮)绑定你的事件:
$('body').on("click", ".yourClass", function () {
//Your code goes here
});
然后使用按钮上的类而不是 ID,将事件侦听器应用于具有给定类的所有按钮。
推荐阅读
- python - 字典可以包含的最大项目数是多少?
- c# - ValidateAntiforgeryToken 不适用于 ASP.NET MVC 中的 Ajax
- java - 解析 json 并获取内部对象
- deep-learning - 神经网络中的时代定义
- r - R 包的 Travis CI:找不到部署密钥
- css - 更改 Jekyll 主题中的字体
- delphi - 发送 TMemoryStream 作为邮件附件
- angular - ng-select 在Angular 6中以编程方式删除元素
- mysql - nodejs mysql - 如何在实际项目中实现 pooledConnection?
- mongodb - Proper way to handle CosmosDb Mongo 429 error with Polly