如何在jQuery的阿贾克斯成功后绑定事件 [英] How to bind event after ajax success in jQuery

查看:141
本文介绍了如何在jQuery的阿贾克斯成功后绑定事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,这里是我的code:

So here is my code:

$(document).ready( function() {
$('#form').bind('change', function(){
    $.ajax({
    type: 'get',
    url: 'api.php',
    data: 'task=getdirs&formname='+$('#form').attr('value'),
    dataType: "text",
    success: function (html){
        $('#chdir').html(html);
        $('#chdir select').bind('change', getDirs());
        }
    });
});
function getDirs(){
}})

#form 这里有一个<选择> 元素。 Ajax调用返回一块HTML的一个新的<选择> 元素
它的工作原理很好:在 #chdir DIV我得到一个新的下拉列表中的元素。但成功在事件部分只触发一次。那么这个事件根本不工作了
我能做些什么,使新创建<选择> 以同样的方式作为第一个元素作品

#form here has a <select> element. The ajax call returns a piece of html with a new <select> element.
It works nice: in the #chdir div I get a new dropdown element. But the event inside the success part fires only once. Then this event does not work anymore at all.
What can I do to make the newly created <select> element work in the same way as the first?

推荐答案

您是直接调用 getDirs 功能绑定方法调用,只应做,如果该函数返回另一个函数,但我认为并非如此。

You are invoking the getDirs function directly on the bind method call, you should only do it if this function returns another function, but I think that's not the case.

修改

$('#chdir select').bind('change', getDirs());

要:

$('#chdir select').bind('change', getDirs);

或者,如果你使用jQuery 1.4及更高版本,可以事件与的变化> 生活 的方法只有一次,你就不会需要重新绑定后,该事件:

Or if you are using jQuery 1.4+, you can bind the change event with the live method only once, and you will not need to re-bind the event after that:

$(document).ready(function () {
  $('#chdir select').live('change', getDirs);
});

这篇关于如何在jQuery的阿贾克斯成功后绑定事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆