简体   繁体   中英

window.addEventListener(“load”,function(){}); does not work

I'm struggling around with a weird problem that shouldn't be too difficult. On every new link that's clicked, I want JS to append a string the the URL. Something like name=MYNAME . Unfortunately it does not work. The event does not get fired at all. Why?

I also tried working with window.onload = myFunction; but it refreshes my url endless of times.

Thank you very much!

Are you using JQuery?

<a href="http://www.google.co.uk">Money?</a>

$(function(){
    // opens a new window to do a Google search for MONEY!!
    $("a").click(function(){
        window.open($(this).attr("href") + "/search?q=is+there+money+in+the+banana+stand");
    });
});

If you don't want a new window change window.open to window.location = $(this).attr...etc .

I just solved my own problem. Hope my solution helps the ones still looking for one!

<script type="text/javascript">
$(document).ready(function(){
    $("a").click(function(){
        var href = $(this).attr("href");

        var character = "";
        if (href.indexOf("?") != -1) {
            character = "&";
        } else {
            character = "?";
        }

        var additionalParams = "name=<?php echo $_GET['name']; ?>&qwer=<?php echo $_GET['qwer']; ?>";

        var url = href + character + additionalParams;
        $(this).attr("href",url);
    });
});
</script>

I simply parsed the URL out of the selected <a> field, edited that url with my parameters and put it back into its href-attribute .

There you go, works like a charm in all browsers.

JAVASCRIPT PURE

<script type="text/javascript">
window.onload = function() {

//// WORK JS EXAMPLE

};
</script>

JQUERY

<script>
jQuery(document).ready(function() {

//// WORK JS EXAMPLE

});
</script>

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