Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

jquery - Responding to click event of element added to document after page load

I am writing a page which uses a lot of in situ editing and updating using jQuery for AJAX.

I have come accross a problem which can best be summarized by the workflow described below:

  1. Clicking on 'element1' on the page results in a jQuery AJAX POST
  2. Data is received in json format
  3. The data received in json format
  4. The received data is used to update an existing element 'results' in the page
  5. The received data is actual an HTML form
  6. I want jQuery to be responsible for POSTing the form when the form button is clicked

The problem arises at point 6 above. I have code in my main page which looks like this:

$(document).ready(function(){
  $('img#inserted_form_btn').click(function(){
   $.ajax({'type': 'POST', 'url': 'www.example.com', 'success': function($data){
      $(data.id).html($data.frm);
     }), 'dataType': 'json'}
  });
});

However, the event is not being triggered. I think this is because when the document is first loaded, the img#inserted_form_btn element does not exist on the page (it is inserted into the DOM as the result of an element being clicked on the page (not shown in the code above - to keep the question short)

My question therefore is: how can I get jQuery to be able to respond to events occuring in elements that were added to the DOM AFTER the page has loaded?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a live handler. deprecated since some time, check the second part of my answer for better solutions!

$('img#inserted_form_btn').live('click', function() {
    // Your click() code
});

Assuming the image is a child of some element that already exists when binding the event, you can use a delegate instead:

$('#parent-element').on('click', '#inserted_form_btn', function() {
    // Your click() code
});

If you do not have jQuery 1.7+:

$('#parent-element').delegate('#inserted_form_btn', 'click', function() {
    // Your click() code
});

In any case, you can use a delegate and use $(document) instead of $('#parent-element') if there is no suitable parent element.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...