使用jQuery将事件处理程序添加到许多动态生成的按钮中 [英] Adding event handler to many dynamically generated buttons with jQuery

查看:88
本文介绍了使用jQuery将事件处理程序添加到许多动态生成的按钮中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动态生成的表格,其中包含代表公司类别的复选框组.这些最终会绘制在动态图表上(此处未显示).每组公司都有一个切换按钮,可以打开或关闭每个类别中的所有复选框.

I have a dynamically generated form with groups of checkboxes representing categories of companies. These eventually get plotted on a dynamic chart (not shown here). Each group of companies has a toggle button to turn all the checkboxes on or off in each category.

对于第一个切换按钮(Tech Giants),我有一个使用其ID的jQuery处理程序,然后相应地选中或取消选中该组中的所有框.

I have a jQuery handler for the first toggle button (Tech Giants) using its ID and then checks or unchecks all the boxes in that group accordingly.

我的问题是这个,它指的是下面块中代码的最后一部分.代替为每个切换按钮手动编写处理程序,我如何创建一个将应用于页面上所有按钮的处理程序?每个按钮应仅选中或取消选中其特定类别中的所有复选框.请注意,页面上的第一个按钮是单独的,不是我们要处理的类别选择复选框的一部分.

My question is this, which refers to the last portion of code in the block below. Instead of manually coding a handler for each toggle button, how can I create one that will apply to all of them on the page? Each button should only check or uncheck all the boxes in its specific category. Note that the first button on the page is separate, and not part of the category selection checkboxes we want to handle.

这是JSFiddle中的代码: https://jsfiddle.net/gq5tw309/

Here's the code in 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>

谢谢!

推荐答案

您可以这样做:将click()事件绑定到所有具有id以"btn" $(document).on("click", "button[id^='btn']", function() {});开头的按钮或仅添加所有切换按钮的类,并将click()事件绑定到它们,这在下面的代码中完成.

You could do it like this: bind the click() event to all buttons that have an id starting with "btn" $(document).on("click", "button[id^='btn']", function() {}); or just add a class to all toggle buttons and bind the click() event to them, which I did in the following code.

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)}" class="category" 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);


$(document).ready(function() {
  $(document).on("click", ".category", function() {
    var buttonData = $(this).data();
    $(this).closest("div").find('input[type=checkbox]').prop('checked', !buttonData.checked);
    buttonData.checked = !buttonData.checked;

  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="button-text" id="customize-button">Open User Settings</button>
<div id="company-selection-form"></div>

这篇关于使用jQuery将事件处理程序添加到许多动态生成的按钮中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆