使用jQuery将事件处理程序添加到许多动态生成的按钮中

问题描述 投票:0回答:1

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

我有一个使用其ID的第一个切换按钮(技术巨人)的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>

谢谢!

javascript jquery forms button
1个回答
0
投票

$('body').on("click", ".yourClass", function () { //Your code goes here });

首先像这样将您的事件绑定到动态生成的html(您的按钮)。并用类名而不是ID绑定事件。

© www.soinside.com 2019 - 2024. All rights reserved.