gpt4 book ai didi

javascript - 绑定(bind)事件到文本节点

转载 作者:搜寻专家 更新时间:2023-11-01 05:26:48 26 4
gpt4 key购买 nike

这是我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com