簡體   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