html标记无法在Javascript中使用

时间:2018-08-09 10:56:59

标签: javascript html

我有一个表单,当我在表单上附加另一个字段时,无法在其他函数中使用它。

<!DOCTYPE html>
<html>
  <head>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
     <script>
        $(document).ready(function(){
          $(".registerNums").click(function(){
              $("#hello").append('<input type="button" value="register" class="inputMems">');
          });
          $(".inputMems").click(function(){
             alert("hi")
         });
       });
   </script>
  </head>
  <body>
    <div>
      <form>
        <div id="hello"></div>
        <input type="button" value="register mems" class="registerNums">
      </form>
    </div>
  </body>
</html>

看我的inputMems按钮不起作用:http://jsfiddle.net/Yelesee/3uecqLxn/

5 个答案:

答案 0 :(得分:9)

要将事件绑定到动态内容中,您需要使用

$(parent_selector).on(event, selector, callback);

因此,从本质上讲,它将事件添加到父元素并检查e.target并在事件与选择器匹配时触发该事件。

因此,您可以使用

$('#hello').on('click', '.inputMems', function(){
    ///do here
});

您还可以做的一件事是附加事件监听器之后,新的dom已创建。

答案 1 :(得分:2)

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(".registerNums").click(function(){
        $("#hello").append('<input type="button" value="register" class="inputMems">');
    });
    $("#hello").on('click','.inputMems',function(){console.log("hi");});
});
</script>
</head>
<body>

<div>
<form>
<div id="hello"></div>

<input type="button" value="register mems" class="registerNums">
</form>
</div>

</body>
</html>

答案 2 :(得分:1)

由于您是根据 id = hello 动态添加DOM元素的, click()无法正常工作。它将对已经存在的元素起作用。它不会绑定到动态创建的元素。为此,您必须使用on()创建一个“委托”绑定。

替换您的点击事件

 $(".inputMems").click(function(){
     alert("hi")
 });

对此!

 $("#hello").on("click", "input.inputMems", function(){
   alert("Here u go!");
 });  

JSFIDDLE

答案 3 :(得分:0)

作为其他答案的替代方法,您可以在创建元素时定义单击处理程序。虽然我确实建议使用.on('click', function(){});

$(document).ready(function() {
  $(".registerNums").click(function() {
    var newInput = $('<input type="button" value="register" class="inputMems">');
    newInput.click(function() {
      alert("hi")
    });
    $("#hello").append(newInput);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <form>
    <div id="hello"></div>

    <input type="button" value="register mems" class="registerNums">
  </form>
</div>

答案 4 :(得分:0)

您已插入

$(".inputMems").click(function(){
alert("hi")
});

$(".registerNums").click(function(){ $("#hello").append('<input type="button" value="register" class="inputMems">'); });内部

应该是这样

$(document).ready(function(){
$(".registerNums").click(function(){
    $("#hello").html('<input type="button" value="register" class="inputMems">');
    $(".inputMems").click(function(){
    alert("hi");
});
});

});