href元素内的内联javascript

时间:2015-11-15 14:00:27

标签: javascript jquery html

在html中我想在href元素

中用#添加当前url

期望的结果将是例如:<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 个答案:

答案 0 :(得分:2)

使用某种公共标记(例如类或data-*属性)标识链接,例如:

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

...然后,一旦您有了基本路径(或者只是在HTML的末尾,就在结束</body>标记之前),请更新其href属性:

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

如果它们应该有不同的散列片段,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"),这不是它的用途。)

答案 1 :(得分:0)

您可以使用:

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