developer tip

동일한 기능을 트리거하는 jQuery 여러 이벤트

optionbox 2020. 9. 28. 09:00
반응형

동일한 기능을 트리거하는 jQuery 여러 이벤트


을 사용하는 방법이 있을까요 keyup, keypress, blur, 및 change이벤트는 한 줄에 같은 함수를 호출하거나 내가 별도로 어떻게해야합니까?

내가 가진 문제는 DB 조회로 일부 데이터의 유효성을 검사해야하고 상자에 입력하거나 붙여 넣는 경우 유효성 검사가 누락되지 않았는지 확인하고 싶습니다.


.on()함수를 여러 이벤트에 바인딩하는 데 사용할 수 있습니다 .

$('#element').on('keyup keypress blur change', function(e) {
    // e.type is the type of event fired
});

또는 일반 이벤트 함수에 매개 변수로 함수를 전달하십시오.

var myFunction = function() {
   ...
}

$('#element')
    .keyup(myFunction)
    .keypress(myFunction)
    .blur(myFunction)
    .change(myFunction)

jQuery 1.7부터이 .on()메서드는 이벤트 핸들러를 문서에 첨부하는 데 선호되는 메서드입니다. 이전 버전의 .bind()경우이 메서드는 이벤트 처리기를 요소에 직접 연결하는 데 사용됩니다.

$(document).on('mouseover mouseout',".brand", function () {
  $(".star").toggleClass("hovered");
})

jQuery가 한 번에 여러 이벤트를 수신 할 때 이벤트 유형을 가져 오는 방법을 찾고 있었고 Google은 여기에 저를 넣었습니다.

그래서 관심있는 사람들을 위해 event.type내 대답은 다음과 같습니다.

$('#element').on('keyup keypress blur change', function(event) {
    alert(event.type); // keyup OR keypress OR blur OR change
});

jQuery 문서 에 더 많은 정보가 있습니다.


당신이 사용할 수있는 바인딩 방법을 몇 가지 이벤트 기능을 첨부 할 수 있습니다. 다음 코드와 같이 이벤트 이름과 핸들러 함수를 전달하면됩니다.

$('#foo').bind('mouseenter mouseleave', function() {
  $(this).toggleClass('entered');
});

또 다른 옵션은 jquery api의 체인 지원을 사용하는 것입니다.


동일한 이벤트 핸들러를 여러 이벤트에 연결하면 한 번에 둘 이상의 이벤트가 실행되는 문제가 자주 발생합니다 (예 : 사용자가 편집 후 탭을 누름, 키 다운, 변경 및 블러가 모두 실행될 수 있음).

실제로 원하는 것은 다음과 같습니다.

$('#ValidatedInput').keydown(function(evt) {
  // If enter is pressed
  if (evt.keyCode === 13) {
    evt.preventDefault();

    // If changes have been made to the input's value, 
    //  blur() will result in a change event being fired.
    this.blur();
  }
});

$('#ValidatedInput').change(function(evt) {
  var valueToValidate = this.value;

  // Your validation callback/logic here.
});

이것이 내가하는 방법이다.

$("input[name='title']").on({
    "change keyup": function(e) {
        var slug = $(this).val().split(" ").join("-").toLowerCase();
        $("input[name='slug']").val(slug);
    },
});

재사용하려는 기능을 아래와 같이 정의 할 수 있습니다.

var foo = function() {...}

And later you can set however many event listeners you want on your object to trigger that function using on('event') leaving a space in between as shown below:

$('#selector').on('keyup keypress blur change paste cut', foo);

The answer by Tatu is how I would intuitively do it, but I have experienced some problems in Internet Explorer with this way of nesting/binding the events, even though it is done through the .on() method.

I havn't been able to pinpoint exactly which versions of jQuery this is the problem with. But I sometimes see the problem in the following versions:

  • 2.0.2
  • 1.10.1
  • 1.6.4
  • Mobile 1.3.0b1
  • Mobile 1.4.2
  • Mobile 1.2.0

My workaround have been to first define the function,

function myFunction() {
    ...
}

and then handle the events individually

// Call individually due to IE not handling binds properly
$(window).on("scroll", myFunction);
$(window).on("resize", myFunction);

This is not the prettiest solution, but it works for me, and I thought I would put it out there to help others that might stumble upon this issue


$("element").on("event1 event2 event..n", function() {
   //execution
});

This tutorial is about handling multiple events.


"Is there a way to have keyup, keypress, blur, and change events call the same function in one line?"

It's possible using .on(), which accepts the following structure: .on( events [, selector ] [, data ], handler ), so you can pass multiple events to this method. In your case it should look like this:

$('#target').on('keyup keypress blur change', function(e) {
    // "e" is an event, you can detect the type of event using "e.type"
});

And here is the live example:

$('#target').on('keyup keypress blur change', function(e) {
  console.log(`"${e.type.toUpperCase()}" event happened`)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="target">


It's simple to implement this with the built-in DOM methods without a big library like jQuery, if you want, it just takes a bit more code - iterate over an array of event names, and add a listener for each:

function validate() {
  // ...
}

const element = document.querySelector('#element');
['keyup', 'keypress', 'blur', 'change'].forEach((eventName) => {
  element.addEventListener(eventName, validate);
});

참고URL : https://stackoverflow.com/questions/2534089/jquery-multiple-events-to-trigger-the-same-function

반응형