将事件绑定到文本节点

2023-12-10

这是我的 HTML。我需要将点击事件绑定到“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

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

  • http://api.jquery.com/contents/
  • http://api.jquery.com/wrap/
  • http://api.jquery.com/parent/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将事件绑定到文本节点 的相关文章