IT TIP

jquery에서 함수를 실행하는 방법

itqueen 2020. 11. 22. 21:02
반응형

jquery에서 함수를 실행하는 방법


저는 프로그래밍 초보자이고 JQuery에 함수를 저장하고 여러 위치에서 실행하는 방법을 알 수 없습니다.

나는 가지고있다:

$(function () {
  $("div.class").click(function(){
    //Doo something

  });

  $("div.secondclass").click(function(){
    //Doo something
  });

});

이제 2 개의 "// Doo somethings"는 동일하며 동일한 코드를 다시 작성하고 싶지 않습니다.

내가 넣으면 :

$(function () {

  function doosomething ()
  {
    //Doo something
  }

  $("div.class").click(doosomething);

  $("div.secondclass").click(doosomething);

});

클릭 할 때만 아니라 페이지로드시 함수를 실행합니다.

이 작업을 올바르게 수행하는 방법은 무엇입니까?

감사!


다음은 잘 작동합니다.

$(function() {

  // Way 1
  function doosomething()
  {
    //Doo something
  }

  // Way 2, equivalent to Way 1
  var doosomething = function() {
    // Doo something
  }

  $("div.class").click(doosomething);

  $("div.secondclass").click(doosomething);

});

기본적으로 사용하는 것과 동일한 범위에서 함수를 선언합니다 (JavaScript는 Closure사용 하여 범위를 결정합니다).

이제 JavaScript의 함수는 다른 객체처럼 동작 doosomething하므로 다음을 사용하여 클릭시 호출 할 함수로 간단히 할당 할 수 있습니다..click(doosomething);

Your function will not execute until you call it using doosomething() (doosomething without the () refers to the function but doesn't call it) or another function calls in (in this case, the click handler).


I would do it this way:

(function($) {
jQuery.fn.doSomething = function() {
   return this.each(function() {
      var $this = $(this);

      $this.click(function(event) {
         event.preventDefault();
         // Your function goes here
      });
   });
};
})(jQuery);

Then on document ready you can do stuff like this:

$(document).ready(function() {
   $('#div1').doSomething();
   $('#div2').doSomething();
});

function doosomething ()
{
  //Doo something
}


$(function () {


  $("div.class").click(doosomething);

  $("div.secondclass").click(doosomething);

});

Alternatively (I'd say preferably), you can do it like this:

$(function () {
  $("div.class, div.secondclass").click(function(){
    //Doo something
  });
});

You can also do this - Since you want one function to be used everywhere, you can do so by directly calling JqueryObject.function(). For example if you want to create your own function to manipulate any CSS on an element:

jQuery.fn.doSomething = function () {
   this.css("position","absolute");
   return this;
}

And the way to call it:

$("#someRandomDiv").doSomething();

Is this the most obfuscated solution possible? I don't believe the idea of jQuery was to create code like this.There's also the presumption that we don't want to bubble events, which is probably wrong.

Simple moving doosomething() outside of $(function(){} will cause it to have global scope and keep the code simple/readable.

참고URL : https://stackoverflow.com/questions/1191833/how-to-run-a-function-in-jquery

반응형