label標簽內含有input元素,點擊事件會觸發兩次


**label標簽內含有input元素,點擊事件會觸發兩次**

   如果你的結構是label內寫input實現點擊文字時候input也有相應。並且,把事件設置在了label上,那么就會執行兩次了。

//html:
    <label class="first"><input type="checkbox"/>第一</label>
    <br/>
    <label class="second"><span>第二</span></label>

    //jQuery
    $('.first').add('.second').off('click').on('click',function () {
        if ($(this).hasClass('selected')) {
            console.log(1);
            $(this).removeClass('selected');
        } else {
            console.log(2);
            $(this).addClass('selected');
        }
    });
    //點擊'first'標簽,事件會觸發兩次,console結果為2和1
    //點擊'second'標簽,事件觸發一次,console結果為2/1
//html:
    <label class="first"><input type="checkbox"/>第一</label>
    <br/>
    <label class="second"><span>第二</span></label>

//jQuery
    $('.first').add('.second').off('click').on('click',function () {
        if ($(this).hasClass('selected')) {
            console.log(1);
            $(this).removeClass('selected');
        } else {
            console.log(2);
            $(this).addClass('selected');
        }
    });
    //點擊'first'標簽,事件會觸發兩次,console結果為2和1
    //點擊'second'標簽,事件觸發一次,console結果為2/1

解決方法:

1、取消事件的默認動作:event.preventDefault();

    <label class="first"><input type="checkbox"/>第一</label>
    $('.first').off('click').on('click',function (event) {
        event.preventDefault();
        if ($(this).hasClass('selected')) {
            console.log(1);
            $(this).removeClass('selected');
        } else {
            console.log(2);
            $(this).addClass('selected');
        }
    });
    //點擊'first'標簽,事件觸發一次,console結果為2/1
2、可以把事件綁定在input元素上。

    <label class="first"><input type="checkbox" class="input"/>第一</label>
    $('.first .input').off('click').on('click',function (event) {
        event.preventDefault();
        if ($(this).hasClass('selected')) {
            console.log(1);
            $(this).removeClass('selected');
        } else {
            console.log(2);
            $(this).addClass('selected');
        }
    });
    //點擊'first'標簽,事件觸發一次,console結果為2/1

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM