2015-11-15 28 views
0

內的HTML我想渲染#當前的URL作爲另外一個HREF元素內內聯JavaScript A HREF元素

期望的結果將是例如:<a href="/Home/Contact#">MyLink</a> 所以我試着用

<a href="javascript: getUrl();">My link</a> 
<script> 
    function getUrl() { 
     return window.location.pathname + '#'; 
    } 
</script> 

在頁面加載實際上從腳本加載這個URL,結果給我一個空白頁面,內容爲/Home/Contact#,再次我只是在我的href元素中渲染這個url,而不是在頁面加載時執行該鏈接。

回答

2

找出一些一種常見的標誌物(如類或data-*屬性)的鏈接,例如:

<a class="the-common-class">My link</a> 

...再一次您有基本路徑(或者僅在HTML結尾處,就在關閉</body>標記之前)更新其href屬性:

$(".the-common-class").href(window.location.pathname + "#"); 

如果他們應該有不同的hash片段,該data-*屬性可能會更好地工作:

<a data-hash="something">My link</a> 

則:

$("a[data-hash]").href(function() { 
    return window.location.pathname + "#" + this.getAttribute("data-hash"); 
}); 

,或者如果您想了解更多的jQuery:

$("a[data-hash]").href(function() { 
    return window.location.pathname + "#" + $(this).attr("data-hash"); 
}); 

(注意:不要使用.data("hash"),這不是它的用途。)

0

您可以使用:

function getUrl() { 
    $(this).attr('href', window.location.pathname + '#'); 
} 
+0

用戶會因第一次點擊無法工作而感到沮喪。 –