简体   繁体   中英

How to disable a function in javascript onclick

I added a redirect function when refresh button or user try to exit the page they get redirected but what I want to happen is this function to be unload or not executed when they click my button

<a onClick="alert(you are going to tweeter);"href="http://twitter.com" class="tweetbutton" >I Like Twitter</a>

so what happens is it conflicts and two alerts shows up, what I was needing is when the tweetbutton button is click the onclick alert will the one to appear then get redirected to twitter.com without the function below being executed

(function() {
    setTimeout(function() {
        var __redirect_to = 'http://facebook.com';

        var _tags = ['btn', 'input'],
            _go, _i, _i2;
        for (_i in _tags) {
            _els = document.getElementsByTagName(_tags[_i]);
            for (_i2 in _go) {
                if ((_tags[_i] == 'input' && _go[_i2].type != 'btn' && _go[_i2].type != 'submit' && _go[_i2].type != 'image') || _go[_i2].target == '_blank') continue;
                _els[_i2].onclick = function() {
                    window.onbeforeunload = function() {};
                }
            }
        }

        window.onbeforeunload = function() {
            setTimeout(function() {
                window.onbeforeunload = function() {};
                setTimeout(function() {
                    document.location.href = __redirect_to;
                });
            });
            return 'you are leaving this page'
        }
    });
});

Update you code as follows:

<a "href="http://twitter.com" class="tweetbutton" >I Like Twitter</a>

Add this to your js

document.addEventListener('click', function (e) {
    if (e.target.className == 'tweetbutton') alert('you are going to twitter');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM