[英]Button click function doesn't work into an HTML variable | How to fix that?
按钮单击功能不适用于HTML
变量,是我错了还是我的代码缺少某些内容? 我是javasctipt
的初学者,这是我第一次使用这种方法,不知道如何解决这个问题。 所以请问,如何解决这个问题? 任何帮助将不胜感激。
这是我的Jquery
代码如下:
$(function(){ var content1 = '<p>This is a paragraph</p><button class="btn">Show other content</button>'; var content2 = '<h1>This is a title</h1>'; $(".button").click(function(){ $(".modal").show(); $(".modal-content").html(content1); }); $(".btn").click(function(){ $(".modal-content").html(content2); console.log(content2); }); });
.modal{ width: 300px; height: 300px; margin: auto; display: none; background: #eee; padding: 20px 0; text-align: center; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="button">Open modal</button> <div class="modal"> <div class="modal-content"></div> </div>
在第二次单击时,您需要从主体委托事件。 由于附加事件时元素不存在于 DOM 中。 所以把这个$(".btn").click(function(){
$("body").on('click', '.btn', function() {
$(function() { var content1 = '<p>This is a paragraph</p><button class="btn">Show other content</button>'; var content2 = '<h1>This is a title</h1>'; $(".button").click(function() { $(".modal").show(); $(".modal-content").html(content1); }); $("body").on('click', '.btn', function() { $(".modal-content").html(content2); console.log(content2); }); });
.modal { width: 300px; hieght: 300px; margin: auto; display: none; background: #eee; padding: 20px 0; text-align: center; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="button">Open modal</button> <div class="modal"> <div class="modal-content"></div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.