找出使用纯JS点击哪个DOM元素

lon*_*ely 3 html javascript dom

我有一个带文本的HTML文档.我想做到的是,当你点击一个上div元素,在iddiv所示.

我试过这个:

window.onload = function() {
  associateIds();
  clicked();
}

function associateIds() {
  var all = document.getElementsByTagName("*");
  var id = -1;
  for (var elem = 0; elem < all.length; elem++) {
    if (all[elem].tagName == "DIV") {
      id++;
      all[elem].setAttribute("id", id);
    }
  }
}

function clicked() {
  document.body.onclick = function(evt) {
    var evt = window.event || evt; //window.event for IE
    if (!evt.target) {
      evt.target = evt.srcElement; //extend target property for IE
    }
    alert(evt.target.id);
  }
}
Run Code Online (Sandbox Code Playgroud)
<div>
  <h1>MAIN TITLE</h1>
</div>

<div>
  <h2>Title</h2>
</div>

<div>
  <p>
    <strong>Alice</strong> was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it,<i> 'and what is the use of a book,'</i> thought
    Alice<i> 'without pictures or conversations?’</i>.
  </p>
</div>

<div>
  <p>
    So she was considering in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a <strong>White Rabbit</strong> with
    pink eyes ran close by her. There was nothing so very remarkable in that; nor did Alice think it so very much out of the way to hear the Rabbit say to itself, <i>'Oh dear! Oh dear! 
			I shall be late!'</i> (when she thought it over afterwards, it occurred to her that she ought to have wondered at this, but at the time it all seemed quite natural). But when the <strong>Rabbit</strong> actually took a watch out of its waistcoat-pocket,
    and looked at it, and then hurried on, <strong>Alice</strong> started to her feet, for it flashed across her mind that she had never before seen a rabbit with either a waistcoat-pocket, or a watch to take out of it, and burning with curiosity, she ran
    across the field after it, and fortunately was just in time to see it pop down a large rabbit-hole under the hedge.
  </p>
</div>

<div>
  <p>
    Down, down, down. Would the fall never come to an end! <i>'I wonder how many miles I've fallen by this time?' she said aloud. 'I must be getting somewhere near the centre of the earth. Let me see: that would be four thousand miles down, I think—'</i> (for,
    you see, <strong>Alice</strong> had learnt several things of this sort in her lessons in the schoolroom, and though this was not a very good opportunity for showing off her knowledge, as there was no one to listen to her, still it was good practice
    to say it over)<i> '—yes, that's about the right distance—but then I wonder what Latitude or Longitude I've got to?' </i>(Alice had no idea what Latitude was, or Longitude either, but thought they were nice grand words to say).
    <p>
</div>
Run Code Online (Sandbox Code Playgroud)

但是当我点击div时,会发生以下情况:

http://i.stack.imgur.com/K7rF3.png

在我的代码中,ID不是静态分配的,而是由函数分配的associateIds().我已经验证该功能可以完成它的工作:

http://i.stack.imgur.com/5KsWw.png

ID在那里,但是当您点击时它们不会显示.

我更喜欢使用纯JavaScript,而不是jQuery.

为什么会这样?我该如何解决?

Zak*_*rki 5

更新了小提琴

添加while循环以获取父级div.


你必须添加parentNode,因为当你点击目标不是div 那个有id孩子的人,所以你必须添加parentNode并循环遍历元素,直到你得到父divid,见下面的代码:

function clicked() {
    document.body.onclick = function(evt) {
        var evt = window.event || evt; //window.event for IE
        if (!evt.target) {
            evt.target = evt.srcElement; //extend target property for IE
        } 

        var parent = evt.target.parentNode;

        while (parent.tagName != 'DIV') {
            parent = parent.parentNode;
        }
        alert(parent.id);
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

  • 你怎么知道它是父母......这仍然是猜测.唯一的方法是走到dom树 (2认同)