开发者

inconsistent jquery behaviour

开发者 https://www.devze.com 2023-01-20 12:18 出处:网络
i have an unusual javascript problem, i have a javascript problem that alternately refuses to work. Basically, on the first click, the jquery function works as it should, deleting the table row, and r

i have an unusual javascript problem, i have a javascript problem that alternately refuses to work. Basically, on the first click, the jquery function works as it should, deleting the table row, and redrawing the table rows:

$(".deleteRow").click(function(e){
                if(confirm("This will delete the selected week. Are you sure?")){
                    $.ajax({
                        type: 'POST',
                        url: 'http://localhost/todo/index.php/home/ajax_delete',
                        data: { page_id : $(this).attr('id') },
                        success: tableRedraw,
                        dataType: 'html'
                    })
                };
                e.preventDefault();
              })

however, if i click the button that triggers this again, it doesnt work. Instead of going through the javascript function, it follows the link (designed for non javascript mode). I cant understand this unusual behaviour, i might have thought that it was caused by the jquery source not being available (for some unknown reason) but i have another function that adds rows to the table, that can be used many times in succession with no problems:

$("#addRow").click(function(e){
                $.ajax({
                        type: 'POST',
                        url: 'http://localhost/todo/index.php/home/ajax_add',
                        success: tableRedraw,
                        dataType: 'html'
                    })
                e.preventDefault();
              })
            })

any help would be hugely app开发者_开发知识库reciated.


I'm guessing it has to do with your tableRedraw method. If it actually destroys the table, and redraws the entire thing, you're also destroying any reference to jQuery managed event handlers.

I'd guess the reason #addRow keeps working is that it's not actually part of the table that is getting redrawn, or is somehow otherwise being spared from being destroyed.

I don't know what your code requirements are, but it would seem wasteful to destroy and redraw an entire table just to add/remove a row (if that is indeed what is happening). Instead it would seem better to target only the individual row that needs manipulation.


Is your tableRedraw removing the elements (with the deleteRow class) and re-creating them ?

if so, you should use the .live() method to bind the click event, as it will persist it to dynamically added elements..

update

You would need to change the

$(".deleteRow").click(function(e){

to

$(".deleteRow").live('click', function(e){
0

精彩评论

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