JQuery 追加按钮

JQuery append button

本文关键字:按钮 追加 JQuery      更新时间:2023-09-26

我是 JQuery 的新手,我试图在堆栈溢出中阅读其他解决方案,但我还不明白。你能帮帮我吗?

我有一个按钮,在调用函数 addQuestion 后附加到页面上。当我单击该按钮时,它不起作用,但是在html中创建的具有相同ID的按钮确实有效。

<!DOCTYPE html>
<html>
  <head>
   <title>Javascript</title>
  </head>
  <body>
  <div id="header">
    <h1>My Site</h1>
  </div>
  
  <div id="content">
    <p ><h2>Question: </h2></p>
      <strong>question 1:</strong> how old am I? <br>
      a) 18 <br>
      b) 17 <br>
      c) 22 <br>
    <br>
    <input id="myAnswer" type="text">
    <button id="addOne">answer</button>
     </div>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"> </script>
 <script>
  $('#addOne').click(function() {
    var theAnswer = $('#myAnswer').val();
    alert(theAnswer);
  });
  
  function addQuestion(questionNo, task, reply){
    $('#content').append("<br><br><br>" + questionNo +  task + "<br>" + reply + "<br>"
    + '<input id="myAnswer" type="text">' + '<button id="addOne">answer</button>' );
   }
 
   addQuestion("<strong> question 2: </strong>", "what's my name", "a) Will <br> b) Peter <br> c) Jeff " );
 
 </script>
 
  </body>
</html>

首先使用该按钮的类而不是 ID。其次,您需要一个面向未来的事件侦听器。第三,命名空间你的组件,以便有一些上下文绑定:

  // Notice we map the answer to the button with a data attribute.
  function addQuestion(id, questionNo, task, reply){
    $('#content').append("<br><br><br>" + questionNo +  task + "<br>" + reply + "<br>"
    + '<input id="myAnswer-' + id + '" type="text">' + '<button class="addOne" data-answer-id="myAnswer-' + id + '">answer</button>' );
   }
  // Notice we bind click on the static container and delegate to a dynamic element.
  $('#content').on('click', '.addOne', function() {
    var theAnswer = $('#' + $(this).data('answer-id')).val();
    alert(theAnswer);
  });
  // Example add - pass in 2 for an ID
  addQuestion(2, "<strong> question 2: </strong>", "what's my name", "a) Will <br> b) Peter <br> c) Jeff " );

工作演示 : http://jsfiddle.net/x231eLc8/

随着按钮的动态添加,您需要使用 jQuery.on() 将事件处理程序附加到新创建的按钮,并且 ID 应该是唯一的,因此请确保使用不同的 id,以防生成多个按钮:

$(document).ready(function() {
    $(document).on('click', '#addOne', function() {
        var theAnswer = $('#myAnswer').val();
        alert(theAnswer);
    });
});

嗨,问题是你不能有两个具有相同ID的按钮。 您可以创建两个不同的按钮..并创建新脚本。

<script>
$('#addOne').click(function() {var theAnswer = $('#myAnswer').val();alert(theAnswer);});
$('#addTwo').click(function() {var theAnswer = $('#myAnswer2').val();alert(theAnswer);});
function addQuestion(questionNo, task, reply){$('#content').append("<br><br><br>" + questionNo +  task + "<br>" + reply + "<br>"+ '<input id="myAnswer2" type="text">' + '<button id="addTwo">answer</button>' );};
addQuestion("<strong> question 2: </strong>", "what's my name", "a) Will <br> b) Peter <br> c) Jeff ");
</script>

或者使用类和"this"字。