How to consume button click inside tag to prevent link being followed?

前端 未结 5 1956
傲寒
傲寒 2021-01-27 01:49

I\'ve added a button inside a link tag, with a little cross image, that I will eventually use to actually remove that element without it following the link also:

<
相关标签:
5条回答
  • 2021-01-27 02:05

    You need return false; at the end of detectClick and you need to return detectClick on your onclick event.

    Explanation: The return value of the event handler tells the browser whether the default browser action should occur. Since clicking on your button by default triggers the click event of its parent, the link, return false; will prevent that default from happening, which is your exact intention.

    0 讨论(0)
  • 2021-01-27 02:06

    <html>
    <head>
    <title>Consume Click Test</title>    
    </head>
    <body>
        <div><a style="border: solid 1px black; vertical-align: middle; display:inline-block;" href="javascript:void 0;"><button style="position: relative; float: right;" onclick="detectClick('Google')"><img src="cross.png"></button>Google</a></div>
    </body>
    </html>
    <script type="text/javascript">
        function detectClick(message){
            window.alert("Detected: " + message);
        }
    </script>

    0 讨论(0)
  • 2021-01-27 02:10
    <script type="text/javascript">
     function detectClick(message){
      window.alert("Detected: " + message);
      return false;
     }
    </script>
    
    0 讨论(0)
  • 2021-01-27 02:19

    First change your function to:

    function detectClick(message){
        window.alert("Detected: " + message);
        return false; // add this line
    }
    

    then change the onclick handler to:

    onclick="return detectClick('Google')" // note the "return"
    

    Please do note that AFAIK the HTML standard does not allow to have a button inside an anchor.

    0 讨论(0)
  • 2021-01-27 02:19

    Remove your href tag from link tag. Add a id to that link tag. And assign the href value in the detectClict(). like-->

    <html>
    <head>
    <title>Consume Click Test</title>    
    </head>
    <body>
        <div><a id = "link" style="border: solid 1px black; vertical-align:middle; display:inline-block;" > <button style="position: relative; float: right;" onclick="detectClick('Google')"><img src="cross.png"></button>Google</a>     </div>
    </body>
    </html>
    <script type="text/javascript">
        function detectClick(message){
            window.alert("Detected: " + message);
            document.getElementById("link").href = "http://www.google.com";
      }
    </script>
    
    0 讨论(0)
提交回复
热议问题