Javascript 两个div中的一个div上的不同单击事件

Javascript 两个div中的一个div上的不同单击事件,javascript,events,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.app

以下是我测试过的代码:

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

问题是,如果单击其中的div,我只需要一个函数调用。我不希望从父div获取函数,如何才能使其成为函数?

您需要使用
event.stopPropagation()


event.stopPropagation()是您需要在内部div click事件上调用的,这可以防止事件继续到父事件绑定。

您需要停止事件传播:

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

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

这不是一个jQuery问题,
stopPropagation
是一个普通的js事件函数。我建议对实际的点击绑定只使用on函数,因为您当前的示例只需要一个。否则,如果你需要更多的东西,请提供一些上下文。谢谢
var div1 = document.createElement('div');
div1.setAttribute('style', 'width:500px;height:500px;background-color:green;');
div1.addEventListener('click', function () {
    alert('div1');
});

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