source

js 파일 내의 함수를 호출하려면 어떻게 해야 합니까?

ittop 2023. 10. 29. 19:57
반응형

js 파일 내의 함수를 호출하려면 어떻게 해야 합니까?

자바스크립트 파일이 있습니다.AppForm.js, 성공적인 ajax post response 후에 다시 초기화하고 싶습니다.

파일 자체가 포함되어 있으며, 그 중에서도

(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) {

});

댄의 답변 덕분에 해결책은 꽤 근접했지만 이벤트가 작동하지 않습니다. 그 이후로 e.preventDefault(); 라고 합니다.

그리고 여기 전체 대본이 있습니다.

(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):

업데이트 1 추가했습니다.window.materialadmin.AppForm.Initilizeajax 응답에서 이벤트가 작동하지 않습니다.

업데이트 2 그리고 여기 포스트백 후 작동하지 않는 코드가 있습니다.

$(".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 () {

            });
        }
    });

당신은 당신의 코드를 전역 함수로 포장할 수 있습니다.

(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) {

});

업데이트 2 관련

위임에 이벤트를 등록해 보십시오.

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

뭔가를 로드하고 응답 후 새 페이지 내용을 렌더링한다고 가정하기 때문에 이전에 등록된 이벤트는 새 요소에 첨부되지 않습니다.위임을 사용하면 이벤트가 연결되어 있기 때문에 요소가 동적으로 DOM에 추가된 후에도(선택하는 선택기와 일치하는 경우) 이벤트가 작동하게 됩니다.document그리고 당신의 단추에서 거품이 났습니다.DOM에서 이벤트를 더 깊게 첨부할 수 있습니다.document동적 내용을 포함하는 요소(즉, 요청을 완료한 후 덮어쓰지 않는 가장 가까운 요소)에 해당합니다.

. 또한 모두에게 고유 클래스를 추가할 수 있습니다..ProductOnlyForDemonstation button, .IncludeInMainPage button, .Active button이벤트를 해당 클래스에 위임합니다(shorter 정의).

포스트백 후에 이벤트가 작동하는지 확인하는 몇 가지

1)$("#products-list")를 사용합니다. html(데이터)는 #products-list의 하위 요소에 연결된 모든 이벤트를 제거합니다.

그렇다면 a) 이벤트 위임 InjQuery를 사용하여 "#products-list"에 이벤트를 한 번만 첨부하면 동적 html 요소에 이벤트를 첨부하는 방법은 무엇입니까?또는 b)$("#products-list")를 사용한 후 모든 하위 항목에 이벤트를 다시 첨부합니다. html(데이터)

2) . html()를 사용하지 마십시오. 왜냐하면 아이들에 대한 모든 jquery data와 이벤트도 제거하기 때문입니다.대신 독립적인 자식 요소를 업데이트합니다.

저도 당신과 같은 문제를 겪은 적이 있습니다.이벤트를 다시 초기화한 후 모든 이벤트가 제대로 작동하지 않습니다.

저는 많은 노력을 해보았고 마침내 문제를 발견했습니다.모든 컨트롤을 재초기화하면 모든 이벤트가 재결합됩니다.

따라서 제대로 발사되지 않습니다. 따라서 컨트롤과 관련된 모든 이벤트의 바인딩을 해제한 다음 모든 컨트롤 에이지언을 초기화하고 모든 이벤트를 바인딩하십시오.


업데이트된 답변

jQuery 1.7 또는 버전을 사용하는 경우 다음 코드를 추가합니다.

$(".ProductOnlyForDemonstation, .IncludeInMainPage, .Active").off();
$('[data-submit="form"]').off('click');
$('textarea.autosize').off('focus');
$('.floating-label .form-control').off('keyup change');
//-----------------
//**PERFORM INIT OF JS FILE**

이 선 앞에//**PERFORM INIT OF JS FILE**

그리고 1.7 이하의 jquery를 사용하고 다음 코드를 사용합니다.

$(".ProductOnlyForDemonstation, .IncludeInMainPage, .Active").unbind();
$('[data-submit="form"]').unbind('click');
$('textarea.autosize').unbind('focus');
$('.floating-label .form-control').unbind('keyup change');
//-----------------
//**PERFORM INIT OF JS FILE**

이 선 앞에//**PERFORM INIT OF JS FILE**

unbind와 관련된 자세한 도움말을 보려면 여기를 클릭하십시오.

오프와 관련된 더 많은 도움을 원하시면 여기를 클릭해주세요. 도움이 되기를 바랍니다.

함수를 호출하려면 다음 사항을 고려해야 합니다.

함수는 호출을 시도하기 전에 동일한 파일 또는 로드된 파일에 정의되어야 합니다.

함수는 호출하려는 함수의 범위보다 같거나 큰 범위에 있어야 합니다.

따라서 다음 예제가 작동해야 합니다.

function fnc1을 first.js에서 선언하고, 두 번째로 fnc1()을 가질 수 있습니다.

first.js :

function fnc1 (){
    alert('test');
}

second.js :

fnc1();
index.html :

<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>

라인을 추가할 수 있습니다.namespace.initialize = p.initialize;코드 끝에 다음과(와)

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

    /* .......  */

    // =================================================
    // DEFINE NAMESPACE
    // =================================================

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

그리고나서,p.initialize로 전세계적으로 사용할 수 있게 되었습니다.materialadmin.initialize, 다음과 같은 다른 파일에서 호출할 수 있습니다.

materialadmin.initialize();

아마도 두가지 해결책이

제1해

다시 로드할 함수로 js 파일을 만듭니다.

<script language="text/javascript">
   function load_js()
   {
      var head= document.getElementsByTagName('head')[0];
      var script= document.createElement('script');
      script.type= 'text/javascript';
      script.src= 'source_file.js';
      head.appendChild(script);
   }
</script>

그리고 당신의 성공을 위해:

.success(function (data) {
  $("#products-list").html(data);      
   load_js();
}).error(function (data) {

});

두번째 해결책

첫 번째 해결책처럼 : 다시 로드할 함수로 js 파일을 만듭니다.

문서 대신 getScript를 사용합니다.write - 파일이 로드되면 콜백도 가능합니다.

설명: GET HTTP 요청을 사용하여 서버에서 자바스크립트 파일을 로드한 후 실행합니다.

따라서 다음을 사용해 볼 수 있습니다.

.success(function (data) {
    $.getScript('your-file.js', function() {

}).error(function (data) {

});

또는 간단히:

jQuery.getScript('my-js.js');

당신은 노력할 것이고, 그게 도움이 된다면 저에게 말해주세요.

ajax url 스크립트의 맨 위에 이 내용을 인쇄하면 간단합니다.

<script src="your-js-to-be-initialized.js"></script>

jquery ajax 코드는 그대로 유지됩니다.각 요청에 대한 스크립트를 인쇄하면 해당 스크립트가 다시 초기화되어 구성 요소에 바인딩됩니다.

$.ajax({
    url: path.php, 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** 
    //path.php should echo/print the <script src="your-js-to-be-initialized.js">

}).error(function (data) {

});

나는 당신의 편집 이력을 보고 당신이 편집한 것을 봤습니다.

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: ''});
    });
};

그래도 이벤트를 활성화하는 방법이라면, 아약스 콜백을 다시 초기화한 후 폼 클릭 및 텍스트 영역 포커스에 대한 구독이 두 개 이상 있는 것이 원인일 수 있습니다.다른 init 작업만 하고 콜백 기능에서 이벤트 바인딩은 제외하는 것을 추천합니다.

이렇게 해보세요.

(function($) {
    "use strict";

    var materialadmin = {};

    var AppForm = function() {
        //closure
        var self = this;

        (function(){
        //todo: init events
        };)();

        //<your AppForm class's props here...>
    };

    materialadmin.Init = function(){
        //create instance of AppForm calss for materialadmin object
        materialadmin.appForm = new AppForm();
    }

    return materialadmin;
//*}(jQuery)); //  syntax mistake, i'm sorry)).*
})(jQuery);

$(document).ready(function(){
    materialadmin.Init();
});

$.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);
    
    materialadmin.Init();
  },
  error: function(){
    alert('error')}
});

jQuery validator를 사용하고 있으므로 의 메서드를 사용하여 양식을 재설정할 수 있습니다.

이 목적을 위해, 당신은 A를 노출할 수 있습니다.reset방법은 다음과 같습니다.

    p.reset = function () {
        // Reset managed form
        $('.form-validate').data('validator').resetForm();

        // Reset custom stuff
        this._initRadioAndCheckbox();
        this._initFloatingLabels();
    };

요청을 게시한 후 양식을 올바르게 재설정하려면 init 내용에서 이벤트 바인딩을 분리해야 합니다. 예를 들어 다음 이벤트 바인딩이 다음에서 이동해야 합니다._initFloatingLabels로._enableEvents:

    // Link submit function
    $('[data-submit="form"]').on('click', function (e) {
        e.preventDefault();
        var formId = $(e.currentTarget).attr('href');
        $(formId).submit();
    });

마지막으로, 당신은 단지 전화를 하면 됩니다.window.materialadmin.AppForm.reset()당신의 POST 요청의 콜백에서.

언급URL : https://stackoverflow.com/questions/36247729/how-can-i-call-a-function-within-a-js-file

반응형