来自div内容而不是来自指定div的click事件的event.target.id

时间:2015-10-27 21:33:33

标签: javascript jquery

我正在尝试为一堆动态生成的div设置点击事件。但是,有时当我点击div时,会调用点击功能,而event.target不是指定点击功能的div。当我发生这种情况时会发生这种情况。点击靠近其文字的div,而不是div内的空白区域。我怎么能阻止这个?

以下是我用来设置div s:

的代码
for (i = 1; i <= pageArray.length; i++) {

    var divName = "div_" + i
    console.log("adding divname with id " + divName);
    console.log("<div id = '" + divName + "' class = 'unselected' style = 'overflow:hidden; background-color: yellow; float:left;'></div>");
    $('#toAppend').append("<div id = '" + divName + "' class = 'unselected' style = 'overflow:hidden; background-color: yellow; float:left;'></div>");
    $("#" + divName);
    .load(pageArray[i - 1]);
    .css("width", Math.round(widthPer * portionDiv));
    .css("height", heightPer).css("background-color", COLORS[i]);
    .css('cursor', 'pointer');

    // expand section user clicks on and collapse other sections
    .click(function(event) {
        console.log(event);
        console.log("here's id " + event.target.id);
        var div = "#div_" + event.target.id.slice(-1);
        console.log("here's div " + div);
    });
}

该代码位于$(document).ready函数中。它似乎运行正常,然后它变得非常缓慢,我开始故障排除并意识到点击并不总是与其关联的div相关。代码正在运行here并带有一些log语句。以下是控制台输出的示例:

accordion.js:24 adding div element with id div_1   <--- so we can see the divs set up properly
accordion.js:24 adding div element with id div_2
accordion.js:24 adding div element with id div_3
accordion.js:24 adding div element with id div_4
accordion.js:35 here's id div_2
2accordion.js:35 here's id     <--- what?!?! seems to think it's being called from contents of div rather than from div
accordion.js:35 here's id div_4
accordion.js:35 here's id 
accordion.js:35 here's id div_2
accordion.js:35 here's id 
accordion.js:35 here's id div_2

我错过了什么?为什么click事件不会独占于其关联的div,我该如何解决?

1 个答案:

答案 0 :(得分:1)

如果您使用event.target,您将获得点击的实际元素,即使它是附加了点击处理程序的元素的子元素。要识别它的父母,您应该使用event.currentTarget

  

在事件遍历DOM时标识事件的当前目标。它始终引用事件处理程序附加到的元素,而不是event.target,它标识事件发生的元素。

Mozilla doc

在您的情况下,target可以是h2currentTarget始终是div本身。