【问题标题】:Second page does not work with Codes in the first page第二页不适用于第一页中的代码
【发布时间】:2023-03-19 08:24:02
【问题描述】:

我有一个主页,当文档准备好时,我通过 ajax 在其上加载了另一个页面,还有一个按钮,当我单击它时,我会显示一个警报,并且我在第二页中也有该按钮。但是当我在该页面中单击它时,该代码不起作用? 我该如何解决这个问题?

因为我不想在第二页重复js codes

这是我的第一页代码:

首页代码:

<html>
<head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

<body>
<div class="captcha" style="border:1px solid red;">
</div>
<div class="details1">cccc</div>
<script>
$(document).ready(function(e) {
$(".captcha").load("/secondpage.htm");
$(".details1").click( function()
{
 alert('button clicked');
}
);

});
</script>
</body>
</html>

这是我用类名验证码加载到 div 中的第二个页面:

第二页代码:

<html>
<head>
</head>
<body>
 <section class="details1"> Details </section>
</body>
</html>

【问题讨论】:

  • filter.inc 加载了吗?
  • @AndreiTodorut 是的,这是第二页

标签: javascript jquery


【解决方案1】:

当您需要即时创建新元素时,您不能使用标准点击等事件。动态创建的元素与现有元素的事件处理程序不同。您必须将事件处理程序动态附加到新创建的元素。

将“点击”替换为“打开”。

 $("body").on("click", ".details1", function(){
 alert('button clicked');
});

【讨论】:

  • @Newman,如果您可以添加解释,这个答案会更有用。
猜你喜欢
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
  • 2014-09-20
相关资源
最近更新 更多