简体   繁体   中英

How to make JavaScript to work when its code is rendered dynamically after performing an AJAX GET request?

I am using Ruby on Rails 3.0.9 and jQuery 1.6.2. I am trying to get JavaScript to work when its code is rendered as a partial template after performing an AJAX HTTP GET request. That is, I have the following code that performs an HTTP GET request:

# The 'articles.html.erb' file

var jqxhr = $jQ.get('http://www.my_web_site.com')
.success(function(data) {
  $jQ('#data_container').replaceWith(data);
})

and this is what returns the HTTP request performed to the 'http://www.my_web_site.com' URL ( note : this is a partial template within some JavaScript code):

# The 'info_articles.html.erb' file

<%= link_to 'Article link', article_path(@article), :id => 'article_link' %>

<script type="text/javascript">
  $jQ('#article_link').click(function(event) {
    event.preventDefault();
    ...
  });
</script>

After the replaceWith function correctly replaces the data somewhere in the web page related to the articles.html.erb template, the Javascript just rendered (that is, that contained in the info_articles.html.erb ) doesn't work. In the above example I am referring to the click event handler: it simply doesn't work as expected.

Why does this happen? How can I solve that issue?

use a jquery live binding in the main document instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM