Add parameters to an URL from a just clicked

后端 未结 2 1649

The scenario is a lot of html files with a lot more of links between them. When I call the first one of them (it would be the index), the link pass several parameters throug

相关标签:
2条回答
  • 2021-01-05 06:19

    This will append a string to anything containing an href-attribute when being clicked:

    window.addEventListener("click", function(e) {
        var href = e.target.getAttribute("href");
        if(href) {
            location.href = href + "?q=stackoverflow";
            e.preventDefault();
        }
    });​
    

    Example here: http://jsfiddle.net/E5Q7P/

    Won't work in < IE9

    0 讨论(0)
  • 2021-01-05 06:25

    Instead of changing the onclick-attribute of each link, or using the onbeforeunload-event, I guess one way would be to attach a clickevent-listener to all anchor-elements when the page loads. The callback could then intercept the browsers default behavior to follow the link. You could then get the src attribute of the a-element that was just clicked, add the desired preferences to the URL and then send the user to the proper location (including preferences) by setting window.location.href to the proper URL.

    There is a great aricle on MDN about event-listeners, that I believe would be helpful to you. Note specially the section about older versions of IE

    A very crude example of what it could look like:

    function callback(e){
      // Get the src of the clicked a-element
      var src = this.src;
      // Add preferences to the url, this need 
      // improvement depending on your needs
      src += "?somesetting=foo";
      // Send user to the url with preferences
      window.location.href = src;
    }
    
    // Get all anchors on page
    var anchors = document.getElementsByTagName("a");
    
    // Loop over the elements and attach listener
    for(i=0 ; i < anchors.length ; i++){
      // Extend with support for older IE if needed
      anchors[i].addEventListener("click", callback, false});
    }​
    
    0 讨论(0)
提交回复
热议问题