简体   繁体   English

将元素添加到DOM后如何选择

[英]How to select element after it was added to DOM

On my HTML I have buttons list and text input field. 在我的HTML上,我有按钮列表和文本输入字段。 Input field is to add extra buttons to my buttons list. 输入字段是向我的按钮列表中添加其他按钮。

On jQuery I have eventListener when one of these buttons with .choices is clicked console log its value. 在jQuery上,当单击带有.choices的这些按钮之一时,我具有eventListener控制台记录其值。

It works fine without any errors. 它工作正常,没有任何错误。 But when I add extra button to my list with same class (.choices) new button appears but it doesn't respond to my click. 但是,当我在具有相同班级(.choices)的列表中添加额外的按钮时,会出现新的按钮,但它不会响应我的点击。

Any suggestions? 有什么建议么?

<div class="buttons">
  <button id="button0" class="choices">Running</button>
  <button id="button1" class="choices">Yoga</button>
  <button id="button2" class="choices">Karate</button> 
</div>

JS JS

$("#add-button").click(function(){
  var inputValue = $("#add-input").val();
  var generatedId = "button" + healthyChoices.length;
  healthyChoices.push(inputValue);
  $("<button>").attr("id", generatedId).appendTo(".buttons");
  $("#" + generatedId).attr("value", inputValue);
  $("#" + generatedId).attr("class", "choices");
  $("#" + generatedId).text(inputValue);
  $("#add-input").val("");
});


$(".choices").click(function(){
  var selectedGroup = $(this).val();
  console.log(selectedGroup);
});

The .click method does not handle elements dynamically added to the DOM. .click方法不处理动态添加到DOM中的元素。 You should be using the .on method (as indicated by dfsq's comment). 您应该使用.on方法(如dfsq的注释所示)。

See this SO post: Difference between .on('click') vs .click() 请参阅此SO帖子: .on('click')与.click()之间的区别

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

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