[英]How To implement the Javascript to elements which has been added to head section of HTML By Jquery prepend()?
I have this in my head section. 我头上有这个。
<script type="text/javascript" src="post.js"></script>
I want this post.js to be also be implemented to the newly created elements.My another js file which is named as main.js have a code that get data from another php file and prepend it in a div with id display.Previous Loaded Div works great with the post.js file but as new elements are prepended, it does not work for new ones. 我希望这个post.js也可以实现到新创建的元素上。我另一个名为main.js的js文件中有一个代码,该代码从另一个php文件中获取数据并将其放在id为display的div中。 Div与post.js文件配合使用非常好,但是由于添加了新元素,因此不适用于新元素。 Here is my main.js code which get data from php file and prepend it: 这是我的main.js代码,该代码从php文件获取数据并进行前置:
var auto_refresh8 = setInterval(function() {
var id = "id="+$(".ally:first").attr("id");
$.ajax({
type: "POST",
url: "get_post.php",
data: id,
cache: false,
success:function(html){
$('#display').prepend(html);
}
});
},2000);
this jquery ajax request get data from get_post.php file and prepend it to the div display. 这个jquery ajax请求从get_post.php文件中获取数据,并将其添加到div显示中。 but the code in post.js doesn't work with this.The data returned by jquery ajax request contains a div with class comm which have to submitted when keypress function acts. 但是post.js中的代码对此不起作用.jquery ajax请求返回的数据包含一个comm类的div,当keypress函数起作用时必须提交。
following is the code of post.js : 以下是post.js的代码:
$(document).ready( function() {
$(".comm").keypress(function(e) {
if(e.which == 13) {
var id = $(this).attr("id");
var data = 'id=' + id;
var post = $(this).val();
var data1 = 'comment='+post;
var wholedata = data+'&'+data1;
$(this).blur();
$.ajax({
type: "POST",
url: "c_insert.php",
data: wholedata,
cache: false,
success:function(html){
$('.class_all'+id).append(html);
}
});
return false;
}
});
});
Use a delegate to handle the event in post.js file instead. 使用委托来处理post.js文件中的事件来代替。 See the jQuery documentation for more information. 有关更多信息,请参见jQuery文档 。
Something like this should do it: 这样的事情应该做到:
$('#display').on('keypress', '.comm', function (e) {
if(e.which == 13) {
// Do code on event
}
});
Note that the "on" function should only be used if you are using jQuery version 1.7 or later. 请注意,仅在使用jQuery 1.7或更高版本时才应使用“ on”功能。 Previous versions uses the function "delegate". 以前的版本使用功能“委托”。
edit Changed $(document).on(...) to $('#display').on(...) since all '.comm'-elements are children of '#display'. 编辑将$(document).on(...)更改为$('#display')。on(...),因为所有'.comm'元素都是'#display'的子元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.