prevent page refresh by submit a post action from a normal clickevent

烈酒焚心 提交于 2019-12-11 15:57:39

问题


my question is Can I prevent a page refresh from this code

As you can see, I submit a post action from a normal click_event, wich I need because live does not support submit events.

jQuery('.verwijder').live('click', function() { 
    t=$(this);

    t.parents(".paneltbnote").animate({ opacity: 'hide' }, "slow",function(){
        t.parents(".wrappertbnote").remove();
        settbnotecounter();

        $db_tbnoteid = t.parents(1).children('.frmnoteid').val();

        $.post("tbnotesact.php", {
            noteid: $db_tbnoteid,
            actie: "verwijder",
            tijd: timestamp
        }, function(xml) {
            // hier nog iets doen
            berichtentoevoegen(xml);//feedback
        });//einde post methode

    });// einde callback animate methode

    return false;    
});//einde binding click event

回答1:


try this:

replace the first line with

jQuery('.verwijder').live('click', function(e) { t=$(this);

and replace return false; with

e.preventDefault();



回答2:


You are returning false in the click event but it's not going to stop the submit action, unfortunately. If you have the option of not using the live event listener, you can always just watch the submit action with the bind() method.

jQuery('.verwijder').bind('submit', function() {
    /* everything as usual... */
    return false;
});

Of course, if that's not an option, you might just have to add some logic into your code that will unbind and then rebind all forms' submit actions to do what you want.

$(function() {
    bind_submits();
    // Let's pretend you have a link that adds forms to your page...
    $('#addForm').live('click', function() {
        add_form();
    });
});

function bind_submits() {
   // We need to unbind first to make we don't multi-bind 
   jQuery('.verwijder').unbind('submit').bind('submit', function() {
        /* everything as usual... */
        return false;
    });
}

function add_form() {
    /* do some stuff to add a form to your layout... */

    // Now reset all current 'submit' binds and add the new one...
    bind_submits();
}

This is what had to be done for all event listeners before the live() method was added (if you didn't use the livequery plugin of course). It's more coding and harder to maintain but there aren't really too many other options at the moment that I'm aware of.

Happy jQuerying...




回答3:


A lot of times, if theres an error in the code, javascript never gets to complete the function up to "return false;" resulting in a page reload. Take off the link for now, and see if any errors pop-up.



来源:https://stackoverflow.com/questions/887712/prevent-page-refresh-by-submit-a-post-action-from-a-normal-clickevent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!