How to create an HTML button that acts like a link?

后端 未结 30 3743
长发绾君心
长发绾君心 2020-11-21 04:18

I would like to create an HTML button that acts like a link. So, when you click the button, it redirects to a page. I would like it to be as accessible as possible.

30条回答
  •  庸人自扰
    2020-11-21 05:17

    I know there have been a lot of answers submitted, but none of them seemed to really nail the problem. Here is my take at a solution:

    1. Use the
      method that the OP is starting with. This works really well, but it sometimes appends a ? to the URL. The ? is the main problem.
    2. Use jQuery/JavaScript to do the link following when JavaScript is enabled so that ? doesn't end up appended to the URL. It will seamlessly fallback to the method for the very small fraction of users who don't have JavaScript enabled.
    3. The JavaScript code uses event delegation so you can attach an event listener before the or
    4. The JavaScript code prevents the default action from happening and then follows the link given in the action attribute.

    JSBin Example (code snippet can't follow links)

    // Listen for any clicks on an element in the document with the `link` class
    $(document).on('click', '.link', function(e) {
        // Prevent the default action (e.g. submit the form)
        e.preventDefault();
    
        // Get the URL specified in the form
        var url = e.target.parentElement.action;
        window.location = url;
    });
    
    
    
        
            
            
            Form buttons as links
        
    
        
            
            
                
                
            
        
    
    

提交回复
热议问题