jquery onchange不能处理动态添加的元素

时间:2017-01-25 08:29:15

标签: javascript jquery html

我正在尝试将更改侦听器设置为动态添加的某些元素,但它不起作用。

这是我的 html文件:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Cool Maths</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script src="js/Constants/Url.js"></script>
        <script src="js/Constants/AdminConstants.js"></script>
        <script src="js/Create%20Level/question.js"></script>
        <script src="js/Create%20Level/listener.js"></script>
        <script src="js/Create%20Level/controller.js"></script>
        <script src="js/Create%20Level/createLevel.js"> </script>
          <link rel="stylesheet" href="css/createLevel.css" >

    </head>
    <body>

        <nav class="navbar navbar-inverse">
            <div class="container-fluid">
                <div class="navbar-header"> <a class="navbar-brand" href="index.html">Cool Maths</a> </div>
                <ul class="nav navbar-nav">
                    <li ><a href="createModule.html">Create Module</a></li>
                    <li ><a href="allModules.html">All Modules</a></li>
                    <li class="active" ><a href="#">Create Level</a></li>
                </ul>
            </div>
        </nav>


        <div class="container">
            <form >
                <input type="text" id="level-name" placeholder="Level Name" class="form-control">
            </form>
            <br/>
            <button onclick="newQuestion()" class="btn btn-primary" id="add-question-button" >Add Question</button><br/>
            <br/><br/>
            <div class="questions" id="all-questions-container">

            </div>
        </div>




    </body>
</html>

这是我的 javascript 文件:

    var i = 0;


$(document).ready(function(){

});




function newQuestion(){
         //I am trying to set on change listener to these elements
 var newQuestionHtml = "<div class='question-container'>"+"<b>Question no "+i+"</b><br/>"+
       "<textarea class='form-control' type='text' id='question"+i+"' placeholder='Question'></textarea><br/>"+
       "<textarea class='form-control' type='text' id='hint"+i+"' placeholder='Hint'></textarea><br/>"+
       "<input class='form-control' type='text' id='answer"+i+"' placeholder='answer'><br/>"+
       "<button class='btn btn-danger' onclick=''>Add Step</button></div>";



     $("#all-questions-container").append(newQuestionHtml);

     var question = new Question(i,"","","","");
     var controller = new Controller(question);

     //this line sets on change listener for the textarea with id question0 which was dynamically added
     $("#answer0").on('change',function(){
       alert("changed");
     });

 i++;

}

正在添加元素,但是当更改textarea的值时,不会显示警报。谁能告诉我哪里出错了?感谢您

0 个答案:

没有答案