Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.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
使用jquery和preventDefault()追加url_Jquery_Url_Append - Fatal编程技术网

使用jquery和preventDefault()追加url

使用jquery和preventDefault()追加url,jquery,url,append,Jquery,Url,Append,我试图使用以下代码在joomla安装中附加一个带有id的url(作为测试) jQuery('body').click(function(e) { e.preventDefault(); window.location = jQuery(this).attr('href') + '#test'; }); 现在,除了在“#test”之前添加字符串“undefined”之外,这在某种程度上是有效的 例如: www.website.com/articles/undefined#te

我试图使用以下代码在joomla安装中附加一个带有id的url(作为测试)

jQuery('body').click(function(e) {
    e.preventDefault();
    window.location = jQuery(this).attr('href') + '#test'; 
}); 
现在,除了在“#test”之前添加字符串“undefined”之外,这在某种程度上是有效的

例如:

www.website.com/articles/undefined#test

为什么要添加“未定义”,有没有办法阻止它


谢谢

这是因为body标签没有
href
属性。这通常适用于链接,即

<a href="some link">Link</a>  

这是因为body标记没有
href
属性。这通常适用于链接,即

<a href="some link">Link</a>  

body标记没有href属性。使用

window.location.hash = '#test';

相反。

body标记没有href属性。使用

window.location.hash = '#test';

相反。

指的是body元素,它没有“href”属性。因此,对
.attr()
的调用返回
未定义的
,它被转换为字符串
“未定义的”

如果只想将“#test”添加到url,则不需要指定完整的URI。相反,您可以只指定相对url,在本例中为“#test”:

如果您试图将“#test”附加到文档中的链接,则只需绑定到具有HREF的链接:

jQuery("a[href]").click(function(e) {
    e.preventDefault();
    location.href = jQuery(this).attr('href') + '#test'; 
}); 
还有几张便条。您不需要使用jQuery来获取href。只需执行以下操作将更简单、更具可读性(IMHO):

location.href = this.href + "#test";
而且,您可以只修改链接的href,而不是阻止默认设置并使用javascript进行导航:

jQuery("a[href]").click(function(e) {
    this.href += "#test";
}); 

指的是body元素,它没有“href”属性。因此,对
.attr()
的调用返回
未定义的
,它被转换为字符串
“未定义的”

如果只想将“#test”添加到url,则不需要指定完整的URI。相反,您可以只指定相对url,在本例中为“#test”:

如果您试图将“#test”附加到文档中的链接,则只需绑定到具有HREF的链接:

jQuery("a[href]").click(function(e) {
    e.preventDefault();
    location.href = jQuery(this).attr('href') + '#test'; 
}); 
还有几张便条。您不需要使用jQuery来获取href。只需执行以下操作将更简单、更具可读性(IMHO):

location.href = this.href + "#test";
而且,您可以只修改链接的href,而不是阻止默认设置并使用javascript进行导航:

jQuery("a[href]").click(function(e) {
    this.href += "#test";
});