开发者

How to dynamically attach behaviors to dynamically loaded elements in HTML using jQuery

开发者 https://www.devze.com 2023-03-13 19:48 出处:网络
I have an HTML form being atta开发者_开发知识库ched to a div element dynamically. How can I attach existing behavior to the newly added elements.

I have an HTML form being atta开发者_开发知识库ched to a div element dynamically. How can I attach existing behavior to the newly added elements.

For example. I have methods like

$.fn.jqueryAjaxFormLoad - defined in jquery.ajaxload.js
$.fn.displayMessage  - defined in jquery.messagebar.js

already defined, which were loaded during page load. Now I want to append or make these available to the newly added form element and its children. What would be a best way to achieve this using jQuery.

The end expectation is that I can call

$('.form_element').displayMessage() on one of the form elements.


You can use the following code to run an event on click of an element:

$("#something").click(function(){
    alert("Something was clicked!");
});

Simply replace click with the event you want to use. You can see a list of the events at this page.

If your event isn't in the list of events at the above link, simply use this code:

$("#something").bind("touchstart",function(){
    alert("You tapped something!");
});

The above code will make an alert appear when the user taps the screen on a mobile device. Simply change touchstart with whatever event you need to use.

Ad@m


You can bind handlers to dynamically added elements using jquery's delegate.


Using jQuery's .live() you can bind event handlers onto objects and the events will be triggered even if new objects are added via AJAX.

http://api.jquery.com/live/

A simple example would be:

$('#foo').live('click', function() {
    // this will be called even if #foo is added minutes after the initial page load!
});
0

精彩评论

暂无评论...
验证码 换一张
取 消