jQuery:将 mouseup 事件附加到容器的所有文本节点
我想在容器的所有节点上附加一个“mouseup”事件,包括使用 jQuery 的文本节点。我该怎么做?
更新:
如果我有一些像这样的 HTML 片段:
<p>Some text node <strong>strong text</strong> another text node.</p>
当前, $("p *") 会将事件应用于
和
<; strong>
但不分别到
内的 2 个文本节点。修改源代码以添加类不是一种选择。
I want to attach a "mouseup" event on all nodes of a container, including text nodes using jQuery. How do I do that?
Update:
If I had some HTML fragment like this:
<p>Some text node <strong>strong text</strong> another text node.</p>
Currently, $("p *") will apply the event to the <p>
and <strong>
but not to the 2 textnodes within <p>
separately. Modifying the source to add classes is not an option.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
bobince 是正确的,您不能在文本节点上设置事件处理程序。听起来您想要类似的东西
,并且事件将附加到 span 标签。但是,如果您无法更改源,那么这将不起作用。
bobince is right that you cannot set event handlers on a Text node. It sounds like you want something like
and the events would get attached to the span tags. However that wouldn't work if you can't change the source.
虽然 Tatu 的答案应该有效(除了使用 .mouseup 而不是 .click),但您确定您确实需要在每个节点上都有一个事件处理程序吗?如果您使用
$('#container').mouseup(function(event){//code})
进行绑定,则事件冒泡模型将在 # 内的任何元素上发生 mouseup 事件时调用相同的函数容器,实际触发事件的 DOM 节点将包含在 event.target 属性中。在大多数情况下,这更加有效。
While Tatu's answer ought to work (except use .mouseup instead of .click), are you sure you actually need an event handler on every single node? If you bind using
$('#container').mouseup(function(event){//code})
the event bubbling model will call that same func anytime the mouseup event occurs on any element inside #container, and the DOM node that actually triggered the event will be contained in the event.target property. This is much more efficient in most cases.
您无法在
Text
节点上设置事件处理程序。文本节点未实现 EventTarget 接口类似于Element
节点、Document
节点和window
对象。你也不应该需要这样做。在父元素上设置一个
mouseup
处理程序,您将获得其所有子内容的mouseup
事件。这是因为mouseup
事件 通过其祖先“冒泡”。You cannot set event handlers on a
Text
node. Text nodes do not implement the EventTarget interface likeElement
nodes, theDocument
node and thewindow
object do.You should never need to, either. Set one
mouseup
handler on the parent element and you will getmouseup
events for all its child content. This is because themouseup
event ‘bubbles’ up through its ancestors.这会将 mouseup 事件处理程序绑定到 #container 内的所有节点。
编辑
更改了点击 ->鼠标向上更清晰。
That will bind the mouseup event handler to all nodes inside #container.
EDIT
Changed click -> mouseup to be clearer.
我认为最简单的方法是向所有节点添加一个类。
jquery 选择器将非常简单:
$('.yourClassName').dostuff()
I think the easiest would be to add a class to all your nodes.
The jquery selector will be as simple as :
$('.yourClassName').dostuff()