我在ajax请求中重新加载html页面后有一个常见的js文件,我无法访问此文件中的函数,$(document).ready(function()之间常见的JS函数 如何访问它们并触发常用文件中的函数 示例:
COMMON JS:
$(document).ready(function() {
$(".agree_btn").click(function(){
alert(123);
});
});
Run Code Online (Sandbox Code Playgroud)
phtml页面中的功能
$('.loadMoreAnswers').live('click', function(event) {
var location_id = $(this).attr('location_id');
var counter= $(this).attr('counter');
$('#loadingAnswer').show();
$.ajax({
type: 'POST',
url: '/daleel/loadmore',
data: 'location_id='+location_id+'&part='+'answers'+'&answerCounter='+counter, //with the page number as a parameter
success: function(msg){
if(msg.length!=0) //if no errors
{ $(this).parent().load("view")
$('#loadingAnswer').remove();
counter+=5;
$('#profile-page-answer').append(msg);
}
else $("#loadingAnswer").remove();
},
dataType: 'html'
});
});
Run Code Online (Sandbox Code Playgroud)
它渲染HTML像这样:
<a agreed="no" agreed-content-id="63066" class="agree_btn" id="agree-a63066">
Agree
</a>
Run Code Online (Sandbox Code Playgroud)
但是,当我点击这个链接时,它不会运行Common JS文件中的函数
在ajax成功中重新绑定click事件处理程序
success: function(msg){
//your code
$(".agree_btn").bind('click');
}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用delegate低于1.7的jQuery版本
$(document).delegate(".agree_btn",'click',function(e){
//your code
});
Run Code Online (Sandbox Code Playgroud)
或者你正在使用jQuery版本1.7+使用on方法
$(document).on("click",".agree_btn",function(e){
//your code
});
Run Code Online (Sandbox Code Playgroud)
不要使用.live已弃用的文档
从jQuery 1.7开始,不推荐使用.live()方法.使用.on()附加事件处理程序.旧版jQuery的用户应该使用.delegate()而不是.live().