How to execute a script after a link is clicked, when browser does not support JavaScript?

后端 未结 3 1609
清酒与你
清酒与你 2021-01-28 04:18

I am trying to use Facebook conversion code like below that includes
both scripts and noscripts tags:


    
      

        
相关标签:
3条回答
  • 2021-01-28 04:36

    Have you tried using the JavaScript onclick event? For example:

    var el; // This is your element pointing to the link you want to handle
    el.onclick = function() {
        // Execute your code here, this event is fired before the default behaviour is executed which is to lead the user to the URL
    };
    

    If your el has an ID of mylink, then you can simply assign el as

    var el = document.getElementById('mylink');
    

    This code becomes even simpler to handle if you're using a JS library like jQuery but for the moment I'm assuming you're not.

    0 讨论(0)
  • 2021-01-28 04:53

    Yes, you can do it.

    put in your link href="javascript:void(0)" and use javascript to redirect.

    <a href="javascript:void(0)" onClick="do_and_redirect()">Your link</a>
    
    <script>
    function do_and_redirect(){
        //SOME CODE
        //..
        //..
        window.location.href = "http://yourpage.com";
    }
    </script>
    
    0 讨论(0)
  • 2021-01-28 04:54

    Here is an edited version of the answer on How to use a link to call JavaScript?

            // Wait for the page to load first
            window.onload = function() {
    
              //Get a reference to the link on the page
              // with an id of "mylink"
              var a = document.getElementById("mylink");
    
              //Set code to run when the link is clicked
              // by assigning a function to "onclick"
              a.onclick = function() {
    
                // Your code here...
    
                //If you don't want the link to actually 
                // redirect the browser to another page,
                // "google.com" in our example here, then
                // return false at the end of this block.
                // Note that this also prevents event bubbling,
                // which is probably what we want here, but won't 
                // always be the case.
                return false;
              }
            }
        </script>
        <noscript><img height="1" width="1" alt="" style="display:none" src="https://www.facebook.com/tr?ev=6030151253043&amp;cd[value]=0.00&amp;cd[currency]=USD&amp;noscript=1" /></noscript>
    </head>
    <body>
        <a id="mylink" href="http://example.com">Link</a>        
    </body>
    </html>
    

    noscript tag will be used only if the browser does not support JavaScript. And that's why you are not going to put any JavaScript there.

    0 讨论(0)
提交回复
热议问题