Fire a function on a element
I need to add a color picker to some input elements. I'm using:
$(".element").colorPicker(){ ... }
This works perfectly.
The problem is that the page has a AJAX form, which - when submitted - will overwrite the previous form with a new one (new input fields etc). After that the colorPicker
stops wo开发者_JS百科rking.
So how can I fire that function to the newly created inputs too?
Just reattach the invocation in the ajax callback, since I don't believe there is a reliable event you can use to .live
or .delegate
it, without revealing more information.
I believe this might work:
$(".element").live('click focus', function () {
var $this = $(this);
if (!$this.data('hasColorPicker')) {
$this.colorPicker({ /* ... */ }).data('hasColorPicker', true);
$this.click(); // trigger the color picker - assuming it binds itself to the click event
}
});
What meder says is good, but also, if you are creating the new elements by copying existing ones, consider using $.clone(true)
to make your copies and it will carry over existing event bindings too.
精彩评论