开发者

Edit the href link before send the request

开发者 https://www.devze.com 2023-03-30 05:13 出处:网络
I have this code : <a class=\"myLink开发者_高级运维\" href=\'http://www.website.it/\'>Link</a>

I have this code :

<a class="myLink开发者_高级运维" href='http://www.website.it/'>Link</a>

<script type="text/javascript">
    var stringToSend = "";
    $('.myLink').click(function() {
        stringToSend="?param=1";
    }); 
</script>

and, as you can see, I'd like to add stringToSend to the href (so the request will be at http://www.website.it/?param=1).

How can I do it?


Just modify the href with new href and you are done.

$('.myLink').click(function() {
    $(this).attr("href", this.href + "?param=1");
});


You should also prevent the default behavior like this:

var stringToSend = "";

// Use this to actually navigate to the changed Uri
$('.myLink').click(function(event) {
    event.preventDefault();
    stringToSend = "?param=1";
    window.location.href = $(this).attr('href') + stringToSend;
}); 

// Use this just to change the Href, without navigating to uri
$('.myLink').click(function(event) {
    event.preventDefault();
    stringToSend = "?param=1";
    var newUri = $(this).attr('href') + stringToSend;
    $(this).attr("href", newUri);
});


When clicking, you could stop the current URL, and navigate to another:

var stringToSend = "";
$('.myLink').click(function() {
    stringToSend="?param=1";
    window.location.href = $(this).attr('href') + stringToSend; // navigate to new URL
    return false; // abort navigation to URL from <a>
}); 


Just set the window.location on your click, and return false to prevent the default behaviour.

A such:

<a class="myLink" href='http://www.website.it/'>Link</a>

<script type="text/javascript">
    var stringToSend = "";
    $('.myLink').click(function() {
        window.location.href = this.href + "?param=" + stringToSend;
        return false;
    }); 
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消