将事件绑定到文本节点

Ben*_*ock 4 javascript jquery events

这是我的HTML.我需要将click事件绑定到"someText"

<div id="container">
    someText <a href="#">A link</a>
</div>
Run Code Online (Sandbox Code Playgroud)

"someText"可以是任何文本字符串

use*_*716 5

使用jQuery用文本节点包装,点击该文本节点<span>.

试一试: http ://jsfiddle.net/3F4p4/

$('#container').contents()  // Get all child nodes (including text nodes)
               .first()     // Grab the first one
               .wrap('<span/>')    // Wrap it with a span
               .parent()           // Traverse up to the span
               .click(function() { alert('hi'); });??  // add the click to the span
Run Code Online (Sandbox Code Playgroud)

.contents()方法返回所有子节点,包括文本节点.因此,您抓住第一个子项,将其换行,遍历到其父项(现在是跨度),然后添加单击.