jQuery的.on()用于jQuery TimeAgo [英] jQuery's .on() for jQuery TimeAgo
问题描述
我正在寻找一种在新插入到页面中的新$("abbr.timeago"
元素上触发.timeago()
函数的方法.现在这就是我在做什么.
I'm looking for a way to trigger the .timeago()
function on new $("abbr.timeago"
elements inserted dynamically into the page. Right now this is what I'm doing.
# Triggered on initial page load
# application.js.coffee
jQuery ->
# Timeago
$("abbr.timeago").timeago()
某些元素被动态替换,我发现将它们插入页面后需要在它们上调用timeago函数.
Some elements are dynamically replaced, and I've found the need to call the timeago function on them after inserting them into the page.
# Triggered after the new abbr.timeago elements have been inserted
// resolve.js.erb
$tweet = $("<%= j render 'conversation_for_tweet', tweet: @tweet %>");
$("#<%= dom_id @tweet, :conversation_for %>").replaceWith($tweet);
$tweet.find("abbr.timeago").timeago();
是否可以绑定到jQuery的.on
函数,以便动态插入的$("abbr.timeago")
标签在之后自动被调用为.timeago()
?
Is there a way to bind to jQuery's .on
function, so that dynamically inserted $("abbr.timeago")
tags are automatically called .timeago()
upon?
相关阅读:
- 使jQuery插件正常工作在动态添加的元素上 =>似乎可以在替换html之前运行jQuery timeago,也许是为了避免某些闪烁.
- https://stackoverflow.com/a/2924202/1606888 =>建议绑定到.on,但是要绑定的事件吗?
- http://www.quirksmode.org/dom/events/ =>找不到要绑定的明显事件.有什么选择吗?
- Making a jQuery Plugin Work On a dynamically added element => seems as if jQuery timeago could be run before replacing the html, maybe to avoid some kind of flash.
- https://stackoverflow.com/a/2924202/1606888 => recomments binding to .on, but what event to bind to?
- http://www.quirksmode.org/dom/events/ => can't find an obvious event to bind to. is there any option?
推荐答案
on
对此无济于事.您可以使用on
将事件处理程序绑定到页面上始终存在的内容,以便在绑定时可以在页面之外的元素上触发事件.在这种情况下,会有所不同.
on
won't help with this. You can use on
to bind an event handler to something which is always on the page so that an event can be triggered on an element not on the page at the time of binding. In this case, it's a little different.
我以前已经解决了此问题,只需在知道情况已发生变化时再次运行$("abbr.timeago").timeago()
即可.
I've solved this before by simply running $("abbr.timeago").timeago()
again when I know things have changed.
这篇关于jQuery的.on()用于jQuery TimeAgo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!