![](/img/trans.png)
[英]Add parameters on href url with javascript and with specific conditions
[英]Add parameters to an URL from a <a href> just clicked
場景是很多html文件,它們之間有很多鏈接。 當我調用它們中的第一個(它將是索引)時,鏈接通過URL傳遞幾個參數(我們可以稱之為首選項)。
現在我想要,當點擊頁面的幾個鏈接中的任何一個時,將添加這些參數。 所以這個問題與其他問題類似( 如何將參數添加到已經包含其他參數且可能是錨點的URL ),但是在點擊鏈接后立即執行此操作。
我知道一個解決方案可能是更改每個鏈接上的onclick事件,但因為可能有數千個,沒有常規的url格式...我正在尋找一個可以在腳本上的解決方案; 也許是與onbeforeunload事件相關的事情。
無論如何,我找不到怎么做。 有任何想法嗎?
這將在單擊時將字符串附加到包含href屬性的任何內容:
window.addEventListener("click", function(e) {
var href = e.target.getAttribute("href");
if(href) {
location.href = href + "?q=stackoverflow";
e.preventDefault();
}
});
示例: http : //jsfiddle.net/E5Q7P/
將無法在<IE9中工作
我想一種方法是在頁面加載時將clickevent-listener附加到所有錨元素,而不是更改每個鏈接的onclick-attribute或使用onbeforeunload-event。 然后,回調可以攔截瀏覽器的默認行為以跟隨鏈接。 然后,您可以獲取剛剛單擊的a元素的src
屬性,將所需的首選項添加到URL,然后通過將window.location.href
設置為正確的URL將用戶發送到正確的位置(包括首選項)。
關於事件聽眾,MDN上有一篇很棒的文章 ,我相信這會對你有所幫助。 請特別注意有關舊版IE的部分
它可能是一個非常粗略的例子:
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});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.