Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

javascript - textNode addEventListener

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/

HTML:

<div contenteditable="true" id="div">A text node, edit me</div>

JavaScript:

var textNode = document.getElementById("div").firstChild;

textNode.addEventListener("DOMCharacterDataModified", function(evt) {
    alert("Text changed from '" + evt.prevValue + "' to '" + evt.newValue + "'");
}, false);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...