繁体   English   中英

html标签无法在Javascript中运行

[英]html tags not working in Javascript

我有一个表格,当我附加另一个字段时,我不能在我的其他功能中使用它。

<!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/

要绑定您需要使用的动态内容中的事件

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

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

所以,在你的情况下,你可以使用,

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

您可以做的另一件事是在创建新dom 之后附加事件侦听器。

 <!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> 

由于您是动态添加DOM元素并引用id = hello ,因此click()不起作用。 它适用于已经存在的元素。 它不会绑定到动态创建的元素。 为此,您必须使用on()创建“委托”绑定。

替换您的点击事件

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

对此!

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

的jsfiddle

作为其他答案的替代方法,您可以在创建元素时定义单击处理程序。 虽然我建议使用.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> 

你有插入

$(".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");
});
});

});

暂无
暂无

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

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