2个DIV上的不同点击事件是另一个

BAS*_*LIO 3 javascript events

这是我测试过的代码:

div1 = document.createElement('div');
div1.setAttribute('style','width:500px;height:500px;background-color:green;');
div1.addEventListener('click',function()
    {
    alert('div1');
    });

div2 = document.createElement('div');
div1.appendChild(div2);
div2.setAttribute('style','width:200px;height:200px;background-color:red;');
div2.addEventListener('click',function()
    {
    alert('div2');
    });
document.getElementsByTagName('body')[0].appendChild(div1);
Run Code Online (Sandbox Code Playgroud)

问题是,如果我单击里面的div,我只需要一个函数调用.我不希望得到父div的功能,怎么可能做?

fla*_*ian 5

你需要使用event.stopPropagation().

div2.addEventListener('click',function(event) {
        event.stopPropagation();// prevents  event from bubbling to parents.
        alert('div2');
}, false);
Run Code Online (Sandbox Code Playgroud)