Development Tip

jQuery $ (“. class”). click ();

yourdevel 2020. 11. 25. 21:18
반응형

jQuery $ (“. class”). click (); -여러 요소, 클릭 이벤트 한 번


동일한 이름의 페이지에 여러 클래스가 있습니다. 그런 다음 JS에 .click () 이벤트가 있습니다. 내가 원하는 것은 내 페이지의 여러 클래스에 관계없이 클릭 이벤트가 한 번만 발생한다는 것입니다.

시나리오는 AJAX를 사용하여 장바구니에 추가하는 것입니다. 때로는 홈 페이지에 추천 제품과 최고 오퍼가있을 수 있습니다. 즉, 동일한 클래스 .add. # productid #가 있고 클릭하면 장바구니에 추가 AJAX가 두 번 실행됩니다.

나는 '클릭 영역'을 만드는 것에 대해 생각하여 .container-name .add. # pid #를 가지므로 고유 한 클릭을 제공합니다.

이것이 유일한 해결책입니까?

<div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>


$(".addproduct").click(function(){//do something fired 5 times});

이 오래된 스레드를 부딪쳐서 죄송합니다. 나는 지금 같은 문제가 있었고 내 해결책을 공유하고 싶었습니다.

$(".yourButtonClass").on('click', function(event){
    event.stopPropagation();
    event.stopImmediatePropagation();
    //(... rest of your JS code)
});

event.StopPropagationevent.StopImmediatePropagation()트릭을 할해야합니다.

이벤트 핸들러에 대한 .class 선택기가 있으면 bubbling클릭 이벤트가 발생합니다 (때로는 부모 요소로, 때로는 DOM의 하위 요소로).

event.StopPropagation()method는 이벤트가 Parent 요소로 버블 링되지 않도록하는 반면 event.StopImmediatePropagation()method는 이벤트가 원하는 클래스 선택기의 Children 요소로 버블 링되지 않도록합니다.

출처 : https://api.jquery.com/event.stoppropagation/ https://api.jquery.com/event.stopimmediatepropagation/


$(document).on('click', '.addproduct', function () {
    // your function here
});

클릭 핸들러를 볼 수 있습니까? 5 개의 다른 요소에 5 명의 리스너를 연결하고 있습니다. 그러나 사용자가 요소를 클릭하면 하나의 이벤트 만 발생합니다.

$(".addproduct").click(function(){
  // Holds the product ID of the clicked element
  var productId = $(this).attr('class').replace('addproduct ', '');

  addToCart(productId);
});

이 솔루션이 작동하지 않으면 클릭 핸들러를 살펴보고 싶습니다.


addproduct class로 div를 클릭하면 5 개가 아닌 특정 요소에 대해 1 개의 이벤트가 발생합니다. 이벤트가 5 번 발생하면 코드에서 뭔가 잘못하고있는 것입니다.


클릭 이벤트를 5 번 추가 한 것 같습니다. 이 일을 몇 번이나 세어보십시오.

console.log('add click event')
$(".addproduct").click(function(){ });

이 상황에서 나는 시도 할 것이다 :

$(document).on('click','.addproduct', function(){

    //your code here

 });

그런 다음 동일한 클래스를 가진 다른 요소에서 하나를 클릭하여 수행해야하는 경우 요소를 반복 할 수 있습니다.

$(document).on('click','.addproduct', function(){
   $('.addproduct').each( function(){

      //your code here
     }
  );
 }
);

이것은 그것을 고쳐야하고 좋은 습관이어야합니다 : .unbind ()

$(".addproduct").unbind().click(function(){
   //do something 
});

인라인 jquery 함수 호출을 사용하여 해결했습니다.

<input type="text" name="testfield" onClick="return testFunction(this)" /> 

<script>
  function testFunction(current){
     // your code go here
  }
</script>

나는 단지 같은 문제가 있었다. 제 경우에는 PHP 코드가 동일한 jQuery 코드를 몇 번 생성했으며 다중 트리거였습니다.

<a href="#popraw" class="report" rel="884(PHP MULTIPLE GENERATER NUMBERS)">Popraw / Zgłoś</a>

(PHP MULTIPLE GENERATER NUMBERS도 동일한 코드를 여러 번 생성했습니다.)

<script type="text/javascript">
$('.report').click(function(){...});
</script>

내 솔루션은 다른 PHP 파일에서 스크립트를 분리하고 해당 파일을 한 번로드하는 것이 었습니다.


여기에 코드를 입력하기 만하면 JQuery에서 ones 이벤트가 트리거됩니다. 파일의 클래스 발생 수를 확인하고 다음 논리에 for 루프를 사용하기 만하면됩니다. JQuery를 통해 클래스, 태그 또는 DOM 요소의 발생 횟수를 식별합니다. var len = $ ( ". addproduct"). length;

 $(".addproduct").click(function(){
       var len = $(".addproduct").length; 
       for(var i=0;i<len;i++){
          ...
        }
 });

내 프로젝트에서 직접 시도했습니다.

테이블의 모든 행에는 "연락처"클래스가 있습니다.

테이블의 모든 행에는 "연락처"클래스가 있습니다.

내 코드는 다음과 같습니다.

var contactManager = {};

contactManager.showEditTools = function(row) {
  console.debug(row);
}

$('.contact').click(function(event){
  console.log("this should appear just once!");
  alert("I hope this will appear just once!");
  contactManager.showEditTools(event);
});

그리고 코드를 실행할 때 Firebug 콘솔의 결과로 전체 행을 보는 것이 처음 무서웠습니다.

코드 실행 후 Firebug 콘솔 스크린 샷

그러나 경고 대화 상자가 나타나지 않았기 때문에 클릭 이벤트가 발생하지 않았 음을 깨달았습니다. Firebug는 클릭 오버라이드의 영향을받는 요소 만 보여줍니다. 따라서 걱정할 것이 없습니다.


.off()핸들러를 사용해보십시오 .

$(function () {
    $(".archive-link").click(function (e) {
        var linkObj = $(this);
        var cb = $("#confirm-modal");
        cb.find(".modal-body").append("<p>Warning message.</p>");
        cb.modal('show'); 
        cb.find(".confirm-yes").click(function () {
            $(this).off(); //detach this event
            //ajax call yada yada..
        }

I attach a click event handler on an OK modal button to act on click event of the object with class .archive-link.

On the first click, the event fires only on that .archive-link object that I asked the function to act on (var linkObj). But when I click the same link the second time and hit OK on the modal, the event fires on every object that has .archive-link that I clicked before.

I used the solutions above but unfortunately did not work. It was when I called .off() within the modal OK button click function that the propagation stopped. I hope this helps.


This question have been resolved and also got a lot of responses, but i want to add something to it. I was trying to figure out, why my click element his firing 77 times, and not one time.

in my code, i had an each, running a json response and displaying it as divs with buttons. And then i declared the click event inside the each.

$(data).each(function(){
    button = $('<button>');
    button.addClass('test-button');
    button.appendTo("body");

    $('.test-button').click(function(){
        console.log('i was clicked');
    })
})

If you write your your code like this, the class .test-button will get multiple click events. For example, my data has 77 lines, so the each will run 77 times, that means i will decline the click event on the class 77 times. When you click the element, it will be fired 77 times.

But if you wirte it like this:

$(data).each(function(){
    button = $('<button>');
    button.addClass('test-button');
    button.appendTo("body");
})

    $('.test-button').click(function(){
        console.log('i was clicked');
    })

you are declaring the click element after the each. That means, the each will run its 77 times, and the click element will be declared only one time. So, if you click the element, it will be fired only one time.


I had the same problem. The cause was that I had the same jquery several times. He was placed in a loop.

$ (". AddProduct"). click (function () {});
$ (". AddProduct"). click (function () {});
$ (". AddProduct"). click (function () {});
$ (". AddProduct"). click (function () {});
$ (". AddProduct"). click (function () {});

For this reason was firing multiple times


이벤트가 한 번만 트리거되므로이 코드가 작동 할 수 있습니다.

    $(".addproduct,.addproduct,.addproduct,.addproduct,.addproduct").click(function(){//do     something fired 5 times});

참고 URL : https://stackoverflow.com/questions/5563783/jquery-class-click-multiple-elements-click-event-once

반응형