鍍金池/ 問答/HTML/ JS input點(diǎn)擊選中

JS input點(diǎn)擊選中

代碼如下
<span class="hidemore">

   <input type="checkbox">按鈕

</span>

效果
clipboard.png

$(".hidemore").click(function () {

    var checked = $(this).find("input").is(':checked');
    if (checked === false) {
        $(this).find("input").prop("checked", "checked");
        $(this).parent().find("span:first-child").find("a").removeClass("on");
    } else if (checked === true) {
        $(this).find("input").removeAttr("checked");
    }
});

這段代碼很奇怪,點(diǎn)擊span的時(shí)候input能打上勾,但是點(diǎn)擊input的時(shí)候勾選不上。
我一直覺得是冒泡原因。
請(qǐng)問下大牛寫還有什么方法
回答
編輯回答
孤星

input 在hidemore中的,你點(diǎn)擊了hidemore會(huì)讓input 也點(diǎn)擊了的,你應(yīng)該把input 冒泡的排除出去
檢測方法:

   $(".hidemore").click(function (e) {
            var checked = $(this).find("input").is(':checked');
            if(event.target.nodeName==="INPUT"){
                console.log(event.target.checked);  //true
            };
            if (checked === false) {
                $(this).find("input").prop("checked", true);
            } else if (checked === true) {
                $(this).find("input").prop("checked",false);
            }
            console.log(event.target.checked);      //false    
        });

可見input改變了兩次

js

  var span = document.getElementsByClassName('hidemore')[0];
        var inp = span.getElementsByTagName('input')[0];
        span.onclick=function(e){
            if(e.target.nodeName==='INPUT'){
                return;
            }else{
                inp.checked = !inp.checked;
            }
        }

jq

      $(".hidemore").click(function (event) {
            var checked = $(this).find("input").is(':checked');
            if(event.target.nodeName==="INPUT")return;
            if (checked === false) {
                $(this).find("input").prop("checked", true);              
            } else{
                $(this).find("input").prop("checked",false);
            }          
        });
2018年7月15日 11:37
編輯回答
情未了

有冒泡吧,你點(diǎn)input也是點(diǎn)到了span,就相當(dāng)于雙擊

2017年3月31日 09:21