简体   繁体   English

单击事件不适用于动态创建的按钮

[英]Click Event not working on dynamically created button

I am trying to create an interactive tutorial using an array of objects which contain a text for the current task.我正在尝试使用包含当前任务文本的对象数组创建交互式教程。

The text creates the task and dynamically attaches a button.文本创建任务并动态附加按钮。

let currentTutorialCount = 0;
var tutorial = [{
    text: "Welcome, I'll be your Task Manager and Guide <button class = 
   'button-next'> Got it</button>",
    set: function () {
      $('#info-container').addClass('non-active');
      $('#canvas-container').addClass('non-active');
      $('#info-container-transparent').css('display', 'block');
      $('#canvas-container-transparent').css('display', 'block');
      $('#suggestion').html(this.text);
    }
  },
  {
    text: "Here you can find information about your String and Current 
    State <button class = 'button-next'>Got it</button>",
    set: function () {
      $('#info-container-transparent').css('display', 'none');
      $('#info-container-text').addClass('highlightBorder');
      $('#info-container-buttons-transparent').css('display', 'block');
      $('#suggestion').html(this.text);
    }
  },
  {
    text: "Here you can generate new Random Graphs and Strings <button 
    class = 'button-next'>Got it</button>",
    set: function () {
      $('#info-container-text').removeClass('highlightBorder');
      $('#info-container-buttons').addClass('highlightBorder');
      $('#info-container-buttons-transparent').css('display', 'none');
      $('#info-container-buttons-transparent').css('display', 'block');
      $('#suggestion').html(this.text);
    }
  }
];` 

When I add the event listener on click on the button the plan is to move to the next task by increasing the currentTutorialCount and call the set function:当我单击按钮添加事件侦听器时,计划是通过增加 currentTutorialCount 并调用 set 函数来移动到下一个任务:

    $('.button-next').click(() => {
     currentTutorialCount += 1;
     tutorial[currentTutorialCount].set();
    });

The DOM structure is as follow: DOM结构如下:

<div id="main-feedback-grid">
  <div id="information">
    <p id="suggestion">Welcome, Make your first transition to the next node</p>
    <button class="answer" value="true">Yes</button>
    <button class="answer" value="false">No</button>
  </div>
</div>

My issue is that the click event only works when I click the button for the first time.我的问题是单击事件仅在我第一次单击按钮时起作用。 I assume the reference of the button is lost every time the set() function creates a new one.我假设每次 set() 函数创建一个新的时,按钮的引用都会丢失。 Any suggestions ?有什么建议 ?

You're running into the classic issue of binding a click event to an element that is not present at runtime.您遇到了将点击事件绑定到运行时不存在的元素的经典问题。 When your script is being evaluated, the element .button-next is not yet present in the DOM, so the click event callback will not be bound to the button.在评估您的脚本时,元素.button-next尚未出现在 DOM 中,因此单击事件回调不会绑定到按钮。

What you want is to rely on event bubbling: you want to listen on an element that is present at runtime, and see if the click event has bubbled from your dynamically-inserted button up to your static element.您想要的是依赖事件冒泡:您想要监听运行时存在的元素,并查看单击事件是否从动态插入的按钮冒泡到静态元素。

Since the button is actually injected as a child node of #suggestion , and #suggestion is guaranteed to be present in the DOM at runtime, you can listen to the click event bubbling up to the #suggestion element instead:由于按钮实际上是作为#suggestion的子节点注入的,并且#suggestion保证在运行时出现在 DOM 中,因此您可以监听点击事件冒泡到#suggestion元素:

$('#suggestion').on('click', '.button-next', () => {
  currentTutorialCount += 1;
  tutorial[currentTutorialCount].set();
});

A helpful tip: always select the closest possible static DOM element when binding your event listener.一个有用的提示:绑定事件侦听时,始终选择最接近的静态 DOM 元素 It is strongly discouraged to listen to bubbling evnets on document or body , because it is expensive (the JS engine has to iterate through all child nodes to find out which one emitted the event).强烈不鼓励在documentbody上监听冒泡事件网络,因为它很昂贵(JS 引擎必须遍历所有子节点以找出哪个子节点发出了事件)。

You can use like below:您可以像下面这样使用:

$("body").find(".button-next").on('click', function(){
   // your code here
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM