Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
href元素中的内联javascript_Javascript_Jquery_Html - Fatal编程技术网

href元素中的内联javascript

href元素中的内联javascript,javascript,jquery,html,Javascript,Jquery,Html,在html中,我想在href元素中添加#作为添加项来呈现当前url 期望的结果将是例如: 所以我试过了 <a href="javascript: getUrl();">My link</a> <script> function getUrl() { return window.location.pathname + '#'; } </script> 函数getUrl(){ 返回window.location.pa

在html中,我想在href元素中添加#作为添加项来呈现当前url

期望的结果将是例如:
所以我试过了

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

函数getUrl(){
返回window.location.pathname+'#';
}
在页面加载时,这实际上是从脚本加载此url,因此给我一个包含
/Home/Contact#
内容的空白页面,我再次只想在我的a href元素中呈现此url,而不是在页面加载时执行该链接。

您可以使用:

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

识别带有某种常见标记(例如类或
data-*
属性)的链接,例如:

<a class="the-common-class">My link</a>
如果它们应该有不同的散列片段,
data-*
属性可能会更好地工作:

<a data-hash="something">My link</a>
或者,如果您想要更多jQuery:

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

(注意:不要使用
.data(“hash”)
,这不是它的用途。)

用户会因为第一次单击不起作用而感到沮丧。
$("a[data-hash]").href(function() {
    return window.location.pathname + "#" + this.getAttribute("data-hash");
});
$("a[data-hash]").href(function() {
    return window.location.pathname + "#" + $(this).attr("data-hash");
});