문제

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()

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();

Is there a way to bind to jQuery's .on function, so that dynamically inserted $("abbr.timeago") tags are automatically called .timeago() upon?

Related reading:

도움이 되었습니까?

해결책

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.

I've solved this before by simply running $("abbr.timeago").timeago() again when I know things have changed.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top