如何在jquery中调用ajax后绑定到另一个事件

时间:2011-02-27 07:09:53

标签: jquery flot

我正在使用flot javascript库创建图表。我启用了可点击事件,div被绑定到plotclick事件。因此,当单击数据点时,将进行ajax调用,并使用结果替换当前div。在此之后我需要将div绑定到一个新事件。

我试图调用bind,但它仍然绑定到旧的回调。当我调用unbind和bind时,不会调用新的回调。

var handleTeacherClick = function( event, pos, item ) {
        if( typeof item != "undefined" && item ) { 
            var user_id = jQuery( 'input[name="id' + item.datapoint[0] + '"]' ).val();
            jQuery.ajax({
                type: 'POST',
                url: BASEPATH + 'index.php/ajax/home/latest',
                data: { "user_id": user_id },
                dataType: 'json',
                success: function ( result ) {
                    jQuery.plot(jQuery('#stats_prog'), 
                        result.progress_data, result.progress_options);
                    jQuery.plot(jQuery('#stats_perf'),
                        result.performance_data, result.performance_options);
                    jQuery('.stats_title').
                        html('<span class="stats_title">'+
                            ' >> Chapter '+Math.ceil(item.datapoint[0])+'</span>');
                        jQuery('#stats_prog')./*unbind("plotclick").*/
                            bind('plotclick', statClickHandler );
                        jQuery('#stats_perf')./*unbind("plotclick"). */
                            bind( 'plotclick', statClickHandler );
                },
            });
        }
    }

3 个答案:

答案 0 :(得分:0)

对于新元素,您应该使用livedelegate。如果您使用的是插件,则可以改为使用livequery

答案 1 :(得分:0)

在您的情况下,使用live而不是绑定事件处理程序

答案 2 :(得分:0)

而不是仅仅调用unbind('plotclick'),明确包含您要取消绑定的函数(使用unbind('plotclick',functionVar)):

jQuery('#stats_prog').unbind("plotclick", handleTeacherClick).
                        bind('plotclick', statClickHandler );