2017-04-19 10 views
1

を「クリック」私は、イベントdeledationを作ってみました身体上のイベントを「クリック」に設定しました。イベントはボタン上で動作します。しかし、なぜそれは体の上で動作しませんか?は、なぜこのような場合には、本体にイベントを動作しません

window.onload = function(){ 
var bodyN = document.body, 
    bodyS = bodyN.style 
bodyS.transition = "all 0s"; 
bodyS.backgroundColor = localStorage.getItem("bgc") 


bodyN.addEventListener("click", function(e){ 
    console.log(e.target);  // why doesn't work this when I click on body? 
    if (e.target.tagName == "BUTTON") { 
     console.log(e); 
     bodyS.transition = ""; 
     bodyS.backgroundColor = e.target.id; 
     localStorage.setItem("bgc", e.target.id); 
    } 
}); 

}

jQueryを介して同じ:

$(document).ready(function(){ 
$("body").css("transition", "all 0s"); 
$("body").css("backgroundColor", localStorage.getItem("bgc")); 

$("body").on("click", "button", function(e){ 
    console.log(e); 
    $("body").css("transition", ""); 
    $("body").css("backgroundColor", e.target.id); 
    localStorage.setItem("bgc", e.target.id); 
}) 

})。 jQueryを使って

答えて

1

、私の代わりに、「オン」のを「クリック」を使用。ここでは例です:

$("body").click(function(e){ 
    console.log(e); 
    if(e.target.id == "button"){ 
     alert('button'); 
    } 
    else{ 
     alert('body'); 
    } 
}); 

https://jsfiddle.net/aumayk6s/

は、それはあなたのお役に立てば幸い!

関連する問題