如何在js文件中调用函数?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (81)

我有一个JavaScript文件AppForm.js,我希望在一个成功的Ajax POST响应之后重新初始化它。

除其他外,该文件本身还包含

(function(namespace, $) {
    "use strict";

    var AppForm = function() {
        // Create reference to this instance
        var o = this;
        // Initialize app when document is ready
        $(document).ready(function() {
            o.initialize();
        });

    };
    var p = AppForm.prototype;

    p.initialize = function() {
        // Init events
        this._enableEvents();

        this._initRadioAndCheckbox();
        this._initFloatingLabels();
        this._initValidation();
    };

    p._enableEvents = function () {
       //blah blah blah
       e.preventDefault();
    };

    p._initRadioAndCheckbox = function () {

    };

    p._initFloatingLabels = function () {

    };

    p._initValidation = function () {

    };

    window.materialadmin.AppForm = new AppForm;
}(this.materialadmin, jQuery)); // pass in (namespace, jQuery):

我该怎么做?

$.ajax({
    url: path, type: "POST", cache: "false",
    dataType: "html",
    contentType: "application/json; charset=utf-8",
    traditional: true,
    data: JSON.stringify(postData)
}).success(function (data) {
    $("#products-list").html(data);
    //**PERFORM INIT OF JS FILE**

}).error(function (data) {

});

这是完整的脚本

(function(namespace, $) {
	"use strict";

	var AppForm = function() {
		// Create reference to this instance
		var o = this;
		// Initialize app when document is ready
		$(document).ready(function() {
			o.initialize();
		});

	};
	var p = AppForm.prototype;

	// =========================================================================
	// INIT
	// =========================================================================

	p.initialize = function() {
		// Init events
		this._enableEvents();
		
		this._initRadioAndCheckbox();
		this._initFloatingLabels();
		this._initValidation();
	};
	
	// =========================================================================
	// EVENTS
	// =========================================================================

	// events
	p._enableEvents = function () {
		var o = this;

		// Link submit function
		$('[data-submit="form"]').on('click', function (e) {
			e.preventDefault();
			var formId = $(e.currentTarget).attr('href');
			$(formId).submit();
		});
		
		// Init textarea autosize
		$('textarea.autosize').on('focus', function () {
			$(this).autosize({append: ''});
		});
	};
	
	// =========================================================================
	// RADIO AND CHECKBOX LISTENERS
	// =========================================================================

	p._initRadioAndCheckbox = function () {
		// Add a span class the styled checkboxes and radio buttons for correct styling
		$('.checkbox-styled input, .radio-styled input').each(function () {
			if ($(this).next('span').length === 0) {
				$(this).after('<span></span>');
			}
		});
	};
	
	// =========================================================================
	// FLOATING LABELS
	// =========================================================================

	p._initFloatingLabels = function () {
		var o = this;

		$('.floating-label .form-control').on('keyup change', function (e) {
			var input = $(e.currentTarget);

			if ($.trim(input.val()) !== '') {
				input.addClass('dirty').removeClass('static');
			} else {
				input.removeClass('dirty').removeClass('static');
			}
		});

		$('.floating-label .form-control').each(function () {
			var input = $(this);

			if ($.trim(input.val()) !== '') {
				input.addClass('static').addClass('dirty');
			}
		});

		$('.form-horizontal .form-control').each(function () {
			$(this).after('<div class="form-control-line"></div>');
		});
	};
	
	// =========================================================================
	// VALIDATION
	// =========================================================================

	p._initValidation = function () {
		if (!$.isFunction($.fn.validate)) {
			return;
		}
		$.validator.setDefaults({
			highlight: function (element) {
				$(element).closest('.form-group').addClass('has-error');
			},
			unhighlight: function (element) {
				$(element).closest('.form-group').removeClass('has-error');
			},
			errorElement: 'span',
			errorClass: 'help-block',
			errorPlacement: function (error, element) {
				if (element.parent('.input-group').length) {
					error.insertAfter(element.parent());
				}
				else if (element.parent('label').length) {
					error.insertAfter(element.parent());
				}
				else {
					error.insertAfter(element);
				}
			}
		});

		$('.form-validate').each(function () {
			var validator = $(this).validate();
			$(this).data('validator', validator);
		});
	};
	
	// =========================================================================
	// DEFINE NAMESPACE
	// =========================================================================

	window.materialadmin.AppForm = new AppForm;
}(this.materialadmin, jQuery)); // pass in (namespace, jQuery):

下面代码不工作

$(".ProductOnlyForDemonstation, .IncludeInMainPage, .Active")
    .on('click', 'button', function(){
        $('.sweet-overlay').toggle();
        if (jQuery("#FORM").valid()) {
            var id = $(this).attr("data-id");
            $.post("/product/DemoIncludeActive", {
                "Id": id,
                "ProductOnlyForDemonstation": $("#ProductOnlyForDemonstation-" + id).is(':checked'),
                "IncludeInMainPage": $("#IncludeInMainPage-" + id).is(':checked'),
                "Active": $("#Active-" + id).is(':checked'),
            },
            function (data) {

            }).success(function (data) {

            }).error(function () {

            });
        }
    });
提问于
用户回答回答于

尝试注册你的事件与委派:

$(document).on(
    'click',
    '.ProductOnlyForDemonstation button, .IncludeInMainPage button, .Active button',
    function() {
        // Your code
    }
);
用户回答回答于

你可以将代码包装在一个全局函数中。

(function(namespace, $) {
  "use strict";
  window.main = function() {
    var AppForm = function () {
    // ...
    };
  };

  window.main(); // you can initialize it here
)(this.materialadmin, jQuery);

如果响应成功,则执行它。

.success(function (data) {
  $("#products-list").html(data);
  //**PERFORM INIT OF JS FILE**
  window.main();
}).error(function (data) {

});

它看起来像是在一个全局对象上公开初始化方法。你可以在Ajax响应完成时调用init方法。

.success(function (data) {
  $("#products-list").html(data);
  //**PERFORM INIT OF JS FILE**
  window.materialadmin.AppForm.initialize();
}).error(function (data) {

});

扫码关注云+社区

领取腾讯云代金券