为了账号安全,请及时绑定邮箱和手机立即绑定

按钮单击功能不适用于 HTML 变量 | 如何解决这个问题?

按钮单击功能不适用于 HTML 变量 | 如何解决这个问题?

梵蒂冈之花 2023-08-05 19:42:28
按钮单击功能不适用于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>
查看完整描述

1 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

在第二次单击中,您需要从正文委托事件。由于附加事件时该元素不存在于 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>


查看完整回答
反对 回复 2023-08-05
  • 1 回答
  • 0 关注
  • 95 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号