页面加载时会触发javascript change事件 - 如何避免这种情况?

时间:2012-02-01 19:19:33

标签: javascript jquery ajax

我有一个带有链式选择框的表单。 zend控制器设置这些选择框的默认值(值来自db)。我是一个jquery新手。

$form->setDefaults($data);

加载了一个jquery文件:

$(document).ready(function(){

        // set up the chained select
        $("#region").remoteChained("#country", "/ws/regionstructure");
        $("#province").remoteChained("#region", "/ws/regionstructure");
        $("#town").remoteChained("#province", "/ws/regionstructure");

     });

问题是,当页面加载时,它会触发国家/地区的更改事件并重置所有选择。

这是被调用的remoteChained jquery代码:

/*
 * Remote Chained - jQuery AJAX(J) chained selects plugin
 *
 * Copyright (c) 2010-2011 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 */

(function($) {

    $.fn.remoteChained = function(parent_selector, url, options) { 

        return this.each(function() {

            /* Save this to self because this changes when scope changes. */            
            var self   = this;
            var backup = $(self).clone();

            /* Handles maximum two parents now. */
            $(parent_selector).each(function() {
                $(this).bind("change", function() {

                    /* Build data array from parents values. */
                    var data = {};
                    $(parent_selector).each(function() {
                        var id = $(this).attr("id");
                        var value = $(":selected", this).val();
                        data[id] = value;
                    });

                    $.getJSON(url, data, function(json) {

                        /* Clear the select. */
                        $("option", self).remove();

                        /* Add new options from json. */
                        for (var key in json) {
                            if (!json.hasOwnProperty(key)) {
                                continue;
                            }
                            /* This sets the default selected. */
                            if ("selected" == key) {
                                continue;
                            }
                            var option = $("<option />").val(key).append(json[key]);
                            $(self).append(option);    
                        }

                        /* Loop option again to set selected. IE needed this... */ 
                        $(self).children().each(function() {
                            if ($(this).val() == json["selected"]) {
                                $(this).attr("selected", "selected");
                            }
                        });

                        /* If we have only the default value disable select. */
                        if (1 == $("option", self).size() && $(self).val() === "") {
                            $(self).attr("disabled", "disabled");
                        } else {
                            $(self).removeAttr("disabled");
                        }

                        /* Force updating the children. */
                        $(self).trigger("change");

                    });
                });

                /* Force updating the children. */
                $(this).trigger("change");             

            });
        });
    };

    /* Alias for those who like to use more English like syntax. */
    $.fn.remoteChainedTo = $.fn.remoteChained;

})(jQuery);

1 个答案:

答案 0 :(得分:0)

我没有看到删除change事件的任何问题,但插件的工作方式似乎非常低效。我重构了这个(未经测试的),所以请试一试,看看它是如何为你工作的。

您可以这样称呼它:

$( "#region" ).remoteChained( { parentSelector: "#country", url: "/ws/regionstructure" } );
$( "#province" ).remoteChained( { parentSelector: "#region", url: "/ws/regionstructure" } );
$( "#town" ).remoteChained( { parentSelector: "#province", url: "/ws/regionstructure" } );

这不应该触发change事件。如果您发现需要这样做,可以执行以下操作:

$( '#region' ).trigger( 'change' );

这是新的插件代码。如果您对此有任何疑问,请与我联系:

( function( $ ) {

    $.fn.remoteChained = function ( options ) {
        var defaults = { },
            settings = $.extend( { }, defaults, options );

        return this.each( function () {

            var el = $( this ),
                parent = $(settings.parentSelector),
                data = { };

            parent.each( function () {
                var el = $(this);
                data[ el.attr( 'id' ) ] = el.find( ':selected' ).val(); 
            });

            parentSelector.bind( 'change.remotechanged', function ( e ) {
                var request = $.ajax( { url: settings.url, data: data } );

                request.done( function ( response ) {
                    var newOption;

                    el.find( 'option' ).remove();

                    for ( var key in response ) {
                        if ( !response.hasOwnProperty( key ) ) {
                            continue;
                        }

                        newOption = $( '<option />' )
                            .val( key )
                            .append( response[ key ] );

                        key === 'selected' && newOption.attr( 'selected', 'selected' );

                        newOption.appendTo( el );
                    }

                    if ( el.find( 'option' ).length === 1 && el.val() === '' ) {
                        el.attr( 'disabled', 'disabled' );
                    } else {
                        el.removeAttr( 'disabled' );
                    }
                });
            });

        });

    };

})( jQuery );