2017-04-19 6 views
1

본문에서 '이벤트'를 설정하려고 '이벤트'를 설정하려고했습니다. 이벤트는 버튼에서 작동합니다. 그러나 왜 그것은 신체에서 효과가 없습니까?이 경우 본체에서 '클릭'이벤트가 작동하지 않습니다.

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

});

답변

1

jQuery에서는 "on"대신 "click"을 사용했습니다. 다음 예는 다음과 같습니다

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

https://jsfiddle.net/aumayk6s/은 당신이 도움이되기를 바랍니다!