source

jQuery 클릭 라벨 클릭 시 두 번 실행됩니다.

manysource 2023. 8. 28. 21:13

jQuery 클릭 라벨 클릭 시 두 번 실행됩니다.

사용자 지정 라디오 버튼을 만들기 위해 jQuery를 사용하고 있는데 문제가 있습니다.라디오와 연결된 레이블을 클릭할 때 클릭 이벤트가 두 번 실행됩니다. 라디오 자체만 클릭하면 정상적으로 작동합니다(사실 제가 클릭하는 것은 라디오가 아니라 전체 입력과 레이블을 감싸는 디브입니다).코드는 다음과 같습니다.

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();

하지만 효과가 없었습니다.그러나 다음을 추가합니다.

evt.stopImmediatePropagation();

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

추가 시도:

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

.vmdk 또는 .click으로 이동합니다.또한 매개 변수를 추가합니다.evt함수에, 예를 들어.function(evt) {...

클릭 이벤트를 레이블이 아닌 입력에 바인딩합니다.더스틴이 언급했듯이 라벨을 클릭하면 입력을 클릭하기 때문에 라벨을 클릭해도 이벤트가 계속 발생합니다.이렇게 하면 레이블이 정상 기능을 유지할 수 있습니다.

$('input').click();

대신에

$('label').click();

외부 컨테이너를 클릭 요소로 사용하려는 경우 이벤트가 자연스럽게 버블링되도록 하고 클릭 핸들러에서 예상되는 요소를 테스트할 수도 있습니다.이 시나리오는 양식의 고유한 클릭 영역을 스타일화하려는 경우에 유용합니다.

<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>

이 문제를 쉽게 해결하려면 레이블에서 "for" 특성을 제거합니다.라벨을 클릭하면 관련 요소도 클릭됩니다.(당신의 경우 클릭 이벤트를 두 번 실행합니다.)

행운을 빌어요

저는 주로 이 신택스를 사용합니다.

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

대신에

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

저는 해결책을 추가하여 시도해 보았습니다.

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

하지만 효과가 없었습니다.

추가함으로써

evt.stopImmediatePropagation();

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

최상의 답변은 댓글 안에 숨겨져 있습니다.

당신은 실제로 결합해야 합니다.change레이블의 텍스트를 클릭할 수 있기 때문에 라디오 단추에서도 항상 라디오 단추 자체를 클릭하지 않습니다.2013년 12월 12일 1시 45분 조비

바이올린은 다른 모든 솔루션을 보여줍니다.stopPropagation,stopImmediatePropagation,preventDefault,return false아무것도 변경하지 않거나 확인란/라디오 기능을 삭제합니다.또한 이것은 jQuery 문제가 아니라 바닐라 자바스크립트 문제임을 보여줍니다.

편집: 다른 스레드에서 찾은 또 다른 작동 솔루션은onclick라벨이 아닌 입력으로 이동합니다.업데이트된 바이올린.

e.preventDefault()의 문제는 라벨 클릭이 라디오 버튼을 확인하지 못하게 하는 것입니다.

더 나은 해결책은 단순히 다음과 같은 "확인됨" 빠른 검사를 추가하는 것입니다.

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

제 문제는 조금 다릅니다.evt.stopPropagation();evt.preventDefault();저한테는 안 먹혀요, 그냥 덧붙이자면요.return false;결국에는, 효과가 있습니다.

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

의 경우, 클릭 이벤트가 함수에 포함되어 있고 함수가 두 번 실행된 것이 문제였습니다.기능을 실행할 때마다 클릭 이벤트가 새로 생성됩니다. -페이스팜-

클릭 이벤트를 기능 밖으로 이동한 후 모든 것이 예상대로 작동했습니다! :)

입력 태그를 트리거 요소 밖에 놓아 보십시오. 레이블 태그는 클릭을 에뮬레이트하므로 항상 두 개 이상의 호출을 수신할 수 있습니다.

저도 같은 문제가 있었습니다. 왜냐하면 제 라디오를 이렇게 레이블 안에 핸들러가 radio_div에 연결된 상태로 중첩했기 때문입니다.중첩 레이블을 제거하면 문제가 해결됩니다.

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

라벨은 확인할 라디오/확인란을 트리거합니다.

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

특히 레이블이 이 동작을 트리거하는 것을 방지합니다.

for="some-id" 특성이 있는 레이블을 클릭하면 대상이 존재하고 입력인 경우에만 새 클릭이 트리거됩니다.e.proventDefault() 등으로 완벽하게 해결할 수 없어서 다음과 같이 했습니다.

예를 들어, 이 구조를 가지고 있고 .some-class를 클릭할 때 이벤트를 원하는 경우

<div class="some-class">
    <input type=checkbox" id="the-input-id" />
    <label for="the-input-id">Label</label>
</div>

효과는 다음과 같습니다.

$(document)
    .on('click', '.some-class', function(e) {
        if(
            $(e.target).is('label[for]')
            &&
            $('input#' + $(e.target).attr('for')).length
        ) {
            // This will trigger a new click so we are out of here
            return;
        }

        // else do your thing here, it will not get called twice
    })
;

네, https://www.w3schools.com/jsref/event_stopimmediatepropagation.asp 을 추가하여 해결했습니다.

e.stopImediatePropagation(); < - 이것은 여러 번의 화재를 막습니다 ⌚

$(document).on("click",".SaveGSTPayableAndRefund",function(e){
   e.stopImmediatePropagation();
})

감사합니다 :)

$(document).on('click','.class',function() {
    alert('abc')
})

에는 이 를 번의경번, 를코우 2기때 2습니사 2다었처럼 포함했기 되었습니다.assets/js/test.js두 번.

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