Why submitting a form overrides setting location.href in a submit button click handler?

前端 未结 3 876
Happy的楠姐
Happy的楠姐 2020-12-20 03:31

This question is inspired by this post.

In a nutshell: Why window.location.href is not redirecting to a new page (example.com) when executing the code be

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-20 03:45

    The main issue is that there is nothing preventing the submit button from actually submitting the form. You would need a return false somewhere for that to happen. I'm not fully certain whether the Submit button logic or the click handler is happening first, but regardless, the form post is taking precedence.

    I was able to get the following to work:

    
    
    
    
    
    

    This example does remove the programmatic addition of the click event, but if that's a hard requirement it should be possible to add that back in.

提交回复
热议问题