最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - textNode addEventListener - Stack Overflow

programmeradmin0浏览0评论

Why can I not add a event listener to the text node itself instead of the p element?

<p>childNode</p>
...
p.childNodes[0].addEventListener('click',function(){alert('ok')},false)

When I click on childNode nothing happens in chrome

Why can I not add a event listener to the text node itself instead of the p element?

<p>childNode</p>
...
p.childNodes[0].addEventListener('click',function(){alert('ok')},false)

When I click on childNode nothing happens in chrome

Share Improve this question asked Jan 25, 2011 at 2:12 Gert CuykensGert Cuykens 7,15514 gold badges53 silver badges87 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 12

April 2021 Update

DOM mutation events such as DOMCharacterDataModified are now deprecated, and MutationObservers should be used instead.

Original answer

Text nodes simply don't fire most events: historically, elements have had the responsibility for doing that in HTML DOMs. However, text nodes do fire some events (except in IE <= 8): DOM mutation events. A particularly useful one for text nodes is DOMCharacterDataModified, which is used to detect change to a text node's text and can be useful in browser-based editors.

Example: http://www.jsfiddle.net/timdown/c6dHX/

document.getElementById("div")
.firstChild.addEventListener(
 "DOMCharacterDataModified",
 function(evt) {
  console.log(
   "Text changed from '"
   + evt.prevValue
   + "' to '"
   + evt.newValue
  );
}, false);
<div contenteditable id="div">Edit me.</div>

Text nodes are just plain "Node" instances, and according to the DOM specs they just can't have event listeners. It's not something that would violate natural law, but it's just not the way the DOM works.

Correction: apparently (thank you Jens) they can have listeners, but most events (including common ones like "click") are not fired on text nodes.

发布评论

评论列表(0)

  1. 暂无评论