为什么点击'在这种情况下,在身体上不起作用

时间:2017-04-19 14:37:14

标签: events event-delegation

我已尝试进行事件审核,设置"点击"身体上的事件。事件适用于按钮。但为什么它不适用于身体呢?

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 个答案:

答案 0 :(得分:1)

使用jQuery,我使用“click”而不是“on”。这是一个例子:

category  lower_bound  upper_bound  cost  modifieddate
--------------------------------------------------
1         0            70456        0     2015-09-29 
1         70456        90000        1.02  2015-09-29 
1         90000        120000       0.88  2015-02-11
1         120000       999999999    0.79  2015-02-11 
2         0            48786        0     2015-11-02
2         48786        50000        0.37  2015-11-02
2         50000        100000       0.21  2015-02-17 
2         100000       175000       0.19  2015-02-17
2         175000       999999999    0.17  2015-02-17
3         0            585969       0.00  2015-11-02
3         585969       999999999    0.02  2015-11-02

https://jsfiddle.net/aumayk6s/

希望它可以帮到你!