How to delegate `hover()` function by using `on()`(如何使用 `on()` 委托 `hover()` 函数)
问题描述
我有一个这样的咖啡代码.
I had a coffee code like this.
$('.foo').hover
(-> $(this).css "cursor", "pointer"),
(-> $(this).css "cursor", "default")
我想将此函数应用于动态附加的 DOM,所以我尝试像这样使用 on()
来委托函数.
And I want to apply this function to dynamically appended DOM, so I tried to delegate function by using on()
like this.
例如,我提到了 这个问题
$(document).on 'hover', '.foo', (event) ->
$(this).css "cursor", "pointer" if event.type is "mouseover"
$(this).css "cursor", "default" if event.type is "mouseout"
但是这段代码根本不起作用.
But this code doesn't work at all.
如何将函数应用于动态添加的元素?
How can I apply the function to dynamically added elements?
推荐答案
我认为您需要取消绑定并添加悬停处理程序.此外,如果要缩进(在这种情况下),则不需要续行.
I think you'll need to unbind and add the hover handler. Also, you don't need the line continuations if you're indenting (in this case).
$( ->
#debugger
addFooDiv = ->
div = $('<div class="foo">This is another foo div</div>')
$(this).parent().append(div)
addFooHandler()
onLeaveHandler = ->
$(this).css "cursor", "pointer"
$(this).css "background", "white"
onEnterHandler = ->
$(this).css "cursor", "default"
$(this).css "background", "lightblue" # so it's real obvious
$('.appendFoo').on('click', addFooDiv)
addFooHandler = ->
$(".foo").unbind("hover")
$(".foo").hover(onEnterHandler, onLeaveHandler)
addFooHandler()
)
http://plnkr.co/edit/JbQtqIOhg2AHBCuoHs4N?p=preview
给 Sethen Maleno 的建议:https://stackoverflow.com/a/9827114/30946
Props to Sethen Maleno: https://stackoverflow.com/a/9827114/30946
这篇关于如何使用 `on()` 委托 `hover()` 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 `on()` 委托 `hover()` 函数


- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01