这是我的 HTML。我需要将点击事件绑定(bind)到“someText”
<div id="container">
someText <a href="#">A link</a>
</div>
"someText"可以是任何文本字符串
最佳答案
使用 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
.contents()
方法返回所有子节点,包括文本节点。因此,您捕获第一个子项,将其包裹起来,遍历到其父项(现在是跨度),然后添加点击。
关于javascript - 绑定(bind)事件到文本节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3142417/