prosource

jQuery를 사용하여 여러 이벤트에서 동일한 기능을 트리거하려면 어떻게 해야 합니까?

probook 2023. 5. 8. 22:18
반응형

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()method는 이벤트 핸들러를 문서에 첨부할 때 선호되는 방법입니다.이전 버전의 경우.bind()메소드는 이벤트 핸들러를 요소에 직접 연결하는 데 사용됩니다.

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

jQuery가 한 번에 여러 이벤트를 들을 때 이벤트 유형을 얻을 수 있는 방법을 찾고 있었는데, 구글이 저를 여기에 배치했습니다.

그래서 관심 있는 분들은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의 체인 지원을 사용하는 것입니다.

가질 수 있는 방법이 있습니까?keyup,keypress,blur,그리고.change이벤트가 한 줄에서 동일한 기능을 호출합니까?

를 사용하면 가능합니다..on()이는 다음 구조를 수용합니다..on( events [, selector ] [, data ], handler )여러 이벤트를 이 메서드에 전달할 수 있습니다.이 경우 다음과 같이 표시됩니다.

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

다음은 실제 사례입니다.

$('#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">

여러 이벤트에 동일한 이벤트 핸들러를 연결하는 경우 두 개 이상의 이벤트가 동시에 발생하는 문제가 발생하는 경우가 많습니다(예: 편집 후 사용자가 탭을 누름, 키다운, 변경 및 흐림이 모두 발생할 수 있음).

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

$('#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() {...}

나중에 아래와 같이 on('event')을 사용하여 해당 기능을 트리거할 이벤트 수신기 수를 설정할 수 있습니다.

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

Tatu의 대답은 제가 직관적으로 그것을 어떻게 할 것인가 하는 것이지만, 저는 이러한 방식으로 이벤트를 중첩/바인딩하는 것과 관련하여 Internet Explorer에서 몇 가지 문제를 경험했습니다.

저는 이것이 어떤 버전의 jQuery에 문제가 있는지 정확히 파악하지 못했습니다.하지만 가끔 다음 버전에서 문제가 발생합니다.

  • 2.0.2
  • 1.10.1
  • 1.6.4
  • 모바일 1.3.0b1
  • 모바일 1.4.2
  • 모바일 1.2.0

저의 해결책은 먼저 함수를 정의하는 것이었습니다.

function myFunction() {
    ...
}

그런 다음 사건을 개별적으로 처리합니다.

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

이것이 가장 예쁜 해결책은 아니지만, 저에게는 효과가 있습니다. 그리고 저는 이 문제를 발견할 수 있는 다른 사람들을 돕기 위해 그것을 내놓아야겠다고 생각했습니다.

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

자습서에서는 여러 이벤트를 처리하는 방법에 대해 설명합니다.

jQuery와 같은 큰 라이브러리 없이 내장된 DOM 메소드를 사용하여 이를 구현하는 것은 간단합니다. 원한다면 코드가 조금 더 필요합니다. 즉, 이벤트 이름 배열을 반복하고 각 항목에 수신기를 추가합니다.

function validate(event) {
  // ...
}

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

둘 이상의 요소에 추가하는 것을 모방하려는 경우:

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

다음 대신:

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

사용할 수 있는 항목:

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

input 때문에 됩니다.keyup keypress blur change에 대한 이벤트paste!

하지만 다중 트리거링을 방지하려면 다음을 수행합니다.

var a;
var foo = function() {
    clearTimeout(a);
    a=setTimeout(function(){
        //your code
        console.log("Runned")
    },50);
}
$('textarea').on('blur change', foo);

언급URL : https://stackoverflow.com/questions/2534089/how-can-i-trigger-the-same-function-from-multiple-events-with-jquery

반응형