jquery click event keeps unbinding
When I run the code the click event works the first time. When I click it more then one time it seems that the click even has unbounded. How do I keep the click event bounded?
var Categories = function() {
$("select[id^='CategoryListBox-']").click(
function() {
开发者_C百科 SelectedItem = $(this).val();
$(this).parent().load('/Categories/CategoryPicker?CatID=' + SelectedItem);
//send CatID to the requesting page
$('form#SubmitPost').prepend('<input id="CatID" name="CatID" type="hidden" value="' + SelectedItem + '" />');
});
}
Categories();
You are overwriting the click handler by replacing the dom inside of it's parent element. You can use live
instead to always keep the binding.
Line 2 would be:
$("select[id^='CategoryListBox-']").live('click',
And that should do it
It looks like you are using AJAX to load new HTML from the server and you're overwriting the existing select box with a new one. This will remove event listeners. One solution is to use live()
:
$("select[id^='CategoryListBox-']").live("click", function() {
SelectedItem = $(this).val();
$(this).parent().load('/Categories/CategoryPicker?CatID=' + SelectedItem);
//send CatID to the requesting page
$('form#SubmitPost').prepend('<input id="CatID" name="CatID" type="hidden" value="' + SelectedItem + '" />');
});
One suggestion: don't use an attribute selector like this. Give all the relevant select boxes a class like "category" and then do:
$("select.category").live("click", function() { ... }
It's much faster.
Lastly, this is a better way of creating your hidden inputs:
$("<input>").attr({id: "CatID", name: "CatID", type: "hidden", value: SelectedItem}).prependTo("#SubmitPost");
The reason being that this creates the DOM element directly rather than interpreting HTML, which again is much slower.
Are you possibly creating/re-creating the object and then failing to re-bind the event? I have one site where we do a fair amount of AJAX updating (using the jQuery taconite plugin), and the last thing we do is explicitly bind the click events on the newly created DOM objects.
I think that when you load() into parent(), you're replacing the original CategoryListBox-* element with a new one. The new one has nothing bound to it. You can either re-bind the function to the new element, which would be ugly and possibly get you into a nasty recursion situation, or you can use the .live() function to bind Categories() to any DOM element with the id of CategoryListBox-*. That would look something like:
$("select[id^='CategoryListBox-']").live('click', function() { [body of your Categories() function] } );
http://api.jquery.com/live/
This will work in jQuery 1.3+. If you're using 1.2, you should upgrade or use the livequery plugin to get similar functionality.
精彩评论