将事件绑定到文本节点
这是我的HTML。 我需要将click事件绑定到“someText”
someText A link
“someText”可以是任何文本字符串
使用jQuery用包装文本节点,点击该位置。
尝试一下: http : //jsfiddle.net/3F4p4/
$('#container').contents() // Get all child nodes (including text nodes) .first() // Grab the first one .wrap('') // Wrap it with a span .parent() // Traverse up to the span .click(function() { alert('hi'); }); // add the click to the span
.contents()
方法返回所有子节点,包括文本节点。 因此,您抓住第一个子项,将其换行,遍历到其父项(现在是跨度),然后添加单击。
经过一番混乱后,我发现帕特里克的解决方案略好一些。 在这种情况下,它可以在链接之后选择节点,使其更加通用。 可能更好的发布在这里:)
$('#container') .contents() .filter(function() { return this.nodeType == Node.TEXT_NODE; }) .wrap('') .parent() .click(function(){ alert($(this).text()); });
没有改变html标记的Hacky方式:
- 向容器添加
contenteditable
属性。 - 单击时,通过
document.getSelection()
查看所选节点并进行检查。 - 如果选择的文本节点是非常节点,请执行您想要的操作。
- 重置选择。
http://jsfiddle.net/quqtk8r6/2/
var el = document.getElementById("container") el.setAttribute("contenteditable", "true") el.style.cursor = "pointer" el.style.outline = "none" el.addEventListener("click", function () { var selection = document.getSelection(), node = selection.baseNode selection.removeAllRanges() if (node.nodeType == 3 && node.parentNode == el) { alert("someText are clicked") } }) el.addEventListener("keydown", function (event) { event.preventDefault() return false })
PS:这是更多的思考,而不是真正的推荐。