Javascript:event.target.id在事件监听器中未定义

时间:2018-06-17 14:41:05

标签: javascript for-loop javascript-events event-handling

我试图在for循环中为多个div添加事件侦听器:

ID~Name~DESC
1~2014~13~DS~DF
1~2014~13~DS~DF
1ABCA B C~ERTE
2~XYZ~ABC  is  bother
3~YYZ~MEL O CRÈME DOUGHNUTS RECLASS
4~XAA~sf sd sdfsf
5~TES~SFSFSFsdfsf
6~ABC"SDDSL dfadf

此代码的问题是,尽管var divElements = document.getElementsByClassName('B'); var vMax = divElements.length; for (var i = 0; i < vMax; i += 1) { divElements[i].addEventListener('DOMCharacterDataModified', function(e) { myFunc(e.target); }, false); } function myFunc(elem) { var text = elem.textContent; var id = elem.id; console.log("text: " + text); console.log("id: " + id); } 正常且文本正确,但text变量未定义,尽管该元素在html中设置了id。这段代码好吗或我错过了什么?

我也尝试了id,但最终导致e.target.getAttribute("id")错误。

2 个答案:

答案 0 :(得分:1)

问题是文本节点是作为大多数元素节点的隐式子节点创建的节点。您正在尝试获取相关文本节点的父元素节点的id,但elem是该节点的子节点,因此您必须访问elem.parentNode.id

我们可以通过检查不同节点的nodeTypenodeName属性来看到这一点。

来自 MDN

  • 元素节点的节点类型为 1
  • 文本节点的节点类型为 3

&#13;
&#13;
var div = document.getElementById("A");
div.addEventListener('DOMCharacterDataModified', function(e) {
  console.log("Target element is a " + e.target.nodeName + " node and has a node type of: " + e.target.nodeType);
  console.log("Target element.parentNode is a " + e.target.parentNode.nodeName + 
               " node and has a node type of: " + e.target.parentNode.nodeType);

  console.log("Target element.text: " + e.target.textContent);
  console.log("Target element.parentNode.id: " + e.target.parentNode.id);
});
&#13;
<h1>Click into the text below and modify it somehow:</h1>
<div id="A" contenteditable>Something</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

看起来你希望传递给myFunc的参数是你要为其分配处理程序的div,所以只需在函数调用中用e.target替换this

var divElements = document.getElementsByClassName('B');
var vMax = divElements.length;
for (var i = 0; i < vMax; i += 1) {
    divElements[i].addEventListener(
      'DOMCharacterDataModified', 
      function(e) {
        myFunc(this);
      },
      false
    );
}

function myFunc(elem) {
    var text = elem.textContent;
    var id = elem.id;
    console.log("text: " + text);
    console.log("id: " + id);
}
<div class='B' id='p1' contenteditable>part 1</div>
<div class='B' id='p2' contenteditable>part 2</div>
<div class='B' id='p3' contenteditable>part 3</div>