开发者

Old jquery click handlers still being active after ID change

I know subject was not clear but I couldn't find a better sentence.

I am building an ajax form. Currently I can save form fields into db via clicking save button and getting values from db with edit button. I also change the #id of save bu开发者_JS百科tton when edit button clicked. But the button still act as it is save button however I change it's #id.

Here is my button:

<a class="btn" id="save_post">Save Post</a>

When I click on edit button I change form values and also change #id of Save Post button;

$('#save_post').attr('id','edit_save_post');

After all, Firebug shows everything OK, #id changed.

<a class="btn" id="edit_save_post">Save Post</a>

But when I click on button it doesn't run update db, it runs again save. How can I have browser forgot old #id?

Thanks,


You most likely bound your handlers using $('...').click(yourfunction); That binds them to the matching elements at this very moment.

If you are adding/changing elements dynamically, use live events: $('...').live('click', yourfunction);

Update:

.live() is deprecated by now; use $(ancestor).on('click', 'selector', yourfunction) instead with ancestor being an element or selector that already exists and contains the related elements selected by selector; to mimic .live() you'd use document as the ancestor.


It sounds like you must have done something like

$('#save_post').click(function() { $.post() // save form stuff });

If that's the case, changing the ID won't work. The click event is bound to the element itself, not the ID. So the behavior won't change.

While you could do a live binding or unbind and rebind the behavior, I think the easiest method is just to have two buttons in the same place, and instead of what you're doing now, use jQuery to toggle() their display. It will look the same to the user, but you can id and bind the buttons separately.


Functions are bound to elements on page load (usually). You can do the folowing:

1) .unbind() the "save" function from button and then bind new "edit" function.

2) Use jQuery .live() to bind function to "edit" button.

3) Bind function to parent element click event (for example to "div" element holding the buttons). Pass event (something like .click(function(event){...});) to that function, check if button was clicked (if (event.target.nodeName == 'BUTTON') and do your logic (if ($(event.target).hasClass('edit')) {....}) I'd recommend 3rd option :)


What I'd suggest is that rather than using one button and rename it to create two buttons and show and hide them depending on current page mode. That way you don't have to do anything like changing IDs that could potentially end up confusing you at a later date.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜