[英]After loading html for a div with jQuery, existing codes/functions doesn't work for loaded content
Maybe you understood from the title however here I go: 也许您从标题中了解了,但是我去了:
I have a file, from that file I load some other data from a php file: 我有一个文件,从该文件中我从php文件中加载了一些其他数据:
File 1 html file 文件1 HTML文件
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function() {
$('#content').load('source.php');
$("#link").click(function() {
alert('Message1!');
return false;
});
});
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
File source.php 文件source.php
<?php
for($i=1;$i<=10;$i++) {
echo '<a href="#" id="link">Link '.$i.'</a>';
}
?>
After the content is loaded from the php file now this code 从php文件加载内容后,此代码
$("#link").click(function() {
alert('Message1!');
return false;
});
doesn't work for loaded content(links). 不适用于加载的内容(链接)。
I need just an explanation how this DOM works, why loaded content can't interact with active functions/codes? 我只需要解释一下此DOM的工作原理,为什么加载的内容无法与活动函数/代码交互?
You should use live() or delegate() if you are using jQuery < 1.7 如果您使用的是jQuery <1.7,则应使用live()或委托()
$("#link").live('click', function() {
alert('Message1!');
return false;
});
$("body").delegate('#link', 'click', function() {
alert('Message1!');
return false;
});
or use on() if you are using jqQuery > 1.7 或使用on()(如果您使用的是jqQuery> 1.7)
$("body").on('click', '#link', function() {
alert('Message1!');
return false;
});
To handle events to DOM objects that are added after page load. 处理页面加载后添加的DOM对象的事件。
Remember that id should be unique on a page this is important. 请记住,id在页面上应该唯一,这一点很重要。 You could do: 您可以这样做:
<?php
for($i=1;$i<=10;$i++) {
echo '<a href="#" class="addedLinks" id="link'.$i.'">Link '.$i.'</a>';
}
?>
and then use the class a selector 然后使用该类的选择器
you just have to use live instead of click for example 您只需要使用实时而不是例如单击
$("#link").live('click', function() {
alert('Message1!');
return false;
});
EDIT : 编辑:
I learned just now that it is deprecated since JQuery 1.7 so now we have to use .on() function like : 我刚刚了解到自JQuery 1.7起不推荐使用它,因此现在我们必须使用.on()函数,例如:
$("#link ").on("click", function(event){
alert('Message1!');
return false;
});
One possible reason is becouse the ID should be unique for your elements in your page, but you are creating 10 of them: 一个可能的原因是因为ID对于页面中的元素应该是唯一的,但是您正在创建10个元素:
for($i=1;$i<=10;$i++) {
echo '<a href="#" id="link">Link '.$i.'</a>';
}
So add an index to the id
for each element or make it class=link
instead. 因此,请为每个元素的id
添加一个索引,或者改为使其为class=link
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.