IT story

레이블을 클릭하면 jQuery Click이 두 번 실행됩니다.

hot-time 2020. 8. 10. 08:08
반응형

레이블을 클릭하면 jQuery Click이 두 번 실행됩니다.


jQuery를 사용하여 사용자 지정 라디오 버튼을 만들고 있는데 문제가 있습니다. 라디오와 관련된 레이블을 클릭하면 클릭 이벤트가 두 번 실행되고 라디오 자체 만 클릭하면 제대로 작동합니다 (실제로 클릭하는 라디오가 아니라 전체 입력 및 레이블을 래핑하는 div). 다음은 코드입니다.

HTML :

 <div id="box">
     <asp:RadioButtonList ID="RadioButtonList1" runat="server">
         <asp:ListItem>RADIO1</asp:ListItem>
         <asp:ListItem>RADIO2</asp:ListItem>
         <asp:ListItem>RADIO3</asp:ListItem>
     </asp:RadioButtonList>
</div>

jQuery :

<script type="text/javascript">
       $(function () {
            $('#box').find('input:radio').each(function (i) {

            var input = $(this);
            // get the associated label using the input's id
            var label = $('label[for=' + input.attr('id') + ']');
            // wrap the input + label in a div
            $('<div class="custom-radio"></div>').insertBefore(input).append(label, input);

            var wrapperDiv = input.parent();

            // find all inputs in this set using the shared name attribute
            var allInputs = $('input[name=' + input.attr('name') + ']');

            // necessary for browsers that don't support the :hover pseudo class on labels
            label.hover(

            function () {
                $(this).addClass('hover');
            }, function () {
                $(this).removeClass('hover checkedHover');
            });

            //bind custom event, trigger it, bind click,focus,blur events
            wrapperDiv.bind('updateState', function () {
                if ($(this)[0].children[1].checked) {
                    allInputs.each(function () {
                        var curDiv = $('div > label[for=' + $(this).attr('id') + ']').parent();
                        curDiv.removeClass('custom-radio-checked');
                        curDiv.addClass('custom-radio');
                    });
                    $(this).toggleClass('custom-radio custom-radio-checked');
                }
                else {
                    $(this).removeClass('custom-radio-checked checkedHover checkedFocus');
                }

            })
            .trigger('updateState')
            .click(function () { console.log('click'); })
            .focus(function () {
                label.addClass('focus');
            }).blur(function () {
                label.removeClass('focus checkedFocus');
            });
        }); 
       });
   </script>

이 동작에 대한 해결책이 있습니까?


추가해보십시오 :

evt.stopPropagation();
evt.preventDefault();

.bind () 또는 .click () 중 표시됩니다. 또한 다음과 같이 매개 변수 evt를 함수에 추가합니다.function(evt) {...


다음을 추가하여 위의 솔루션을 추가해 보았습니다.

evt.stopPropagation();
evt.preventDefault();

하지만 작동하지 않았습니다. 그러나 이것을 추가 :

evt.stopImmediatePropagation();

문제를 해결했습니다! :)


Bind the click event to the input rather than the label. When the label is clicked - the event will still occur because, as Dustin mentioned, a click on the label triggers a click on the input. This will allow the label to hold its normal functionality.

$('input').click();

Instead of

$('label').click();

If you're trying to use an outer container as a click element you can also let the events bubble naturally and test for the expected element in your click handler. This scenario is useful if you're trying to style a unique click zone for a form.

<form>
<div id="outer">
    <label for="mycheckbox">My Checkbox</label>
    <input type="checkbox" name="mycheckbox" id="mycheckbox" value="on"/>
</div>
</form>
<script>
$('#outer').on('click', function(e){
    // this fires for #outer, label, and input
    if (e.target.tagName == 'INPUT'){
        // only interested in input
        console.log(this);
    }
});
</script>

To fix this the easy way, remove the "for" attribute on the label. A click on the label will also trigger a click on the associated element. (which in your case is firing your click event twice.)

Good luck


I usually use this synthax

.off('click').on('click', function () { console.log('click'); })

instead of

.click(function () { console.log('click'); })

Best answer is hidden inside comments:

you should actually bind to change even on the radio button since the text of a label is clickable -- they don't always click the radio button itself. – chovy Dec 12 '13 at 1:45

This fiddle illustrates that all the other solutions – stopPropagation, stopImmediatePropagation, preventDefault, return false – either change nothing or destroy the checkbox/radio functionality). It also illustrates that this is a vanilla JavaScript problem, not a jQuery problem.

EDIT: Another working solution that I just found in another thread is to bind the onclick to the input rather than the label. Updated fiddle.


The problem with e.preventDefault(); is it stops the label click from checking the radio button.

A better solution would be to simply add a "is checked" quick check like so:

$("label").click(function(e){
  var rbtn = $(this).find("input");
  if(rbtn.is(':checked')){
  **All the code you want to have happen on click**
  }
)};

My problem is a bit different, as the evt.stopPropagation();evt.preventDefault(); doesn't work for me, I just add return false; in the end, then it works.

$("#addressDiv").on("click", ".goEditAddress", function(event) {
    alert("halo");
    return false;
});

In my case the problem was that i had the click event in a function and the function was executed twice.... every execution of the function creates a new click event. -facepalm-

after moving the click event outside the function, everything worked as expected! :)


I have tried by adding solution.

evt.stopPropagation();
evt.preventDefault();

but didn't work.

By adding

evt.stopImmediatePropagation();

solved the problem! :)


Try put your input tag outside trigger element, because label tag emulates click, so you will have always more than one call.


I had the same issue because I had nested my radio inside the label like this with the handler attached to radio_div. Removing the nested label fixed the issue.

<div id="radio_div">
    <label>
       <input type="radio" class="community_radio" name="community_radio" value="existing">
           Add To Existing Community
    </label>
</div>

The label triggers the radio/checkbox to be checked.

if ($(event.target).is('label')){
    event.preventDefault();
}

It prevent especially the label to trigger this behavior.

참고URL : https://stackoverflow.com/questions/8238599/jquery-click-fires-twice-when-clicking-on-label

반응형