[英]How not to change the web page URL?
我需要使用jQuery mobile设置相对于当前页面URL的按钮的href值。
所以我天真地写了以下代码:
var path = window.location;
path = path.replace( "shop","edit" );
$("#btnEdit").setAttr( "href", path );
页面的网址为http:// mysite / shop / 1 ,按钮的href设置为http:// mysite / edit / 1 。
当将此代码插入“ pageinit”处理程序的顶部时,我看到浏览器(firefox和chrome)的位置栏中的URL更改为http:// mysite / shop / shop ,并且页面显然已重新加载,所以我出现404错误,因为它必须在/ shop /之后有一个数字,并且其值应为1。
即使我注释掉了,重新启动Web服务器,浏览器也会在其url位置字段中将http:// mysite / shop / 1替换为http:// mysite / shop / shop 。 ?!
我必须评论这些说明,重新启动服务器以及避免这种URL替换的方法。
到底是怎么回事 ? 如何获得页面位置URL并设置按钮href值,而又没有这种讨厌的副作用?
编辑1:
编辑2:
解:
在html文件中,我使用默认的href值定义了此按钮,没什么特别的:
<a href="#" data-role="button" data-icon="pencil" id="btnEdit"> Edit </a>
在脚本文件中,更确切地说,在$(document).on('pageinit',...)的处理程序中,我现在有了这段代码,该代码设置href值,但还将rel =“ external”属性添加到按钮。
var path = window.location.href;
path = path.replace( "shop","edit" );
$("#btnEdit").attr( "href", path ).attr( "rel", "external" );
没有更多的页面自动重新加载,并且已删除了奇怪的加载行为。 发生这种情况是因为jQuery Mobile中<a>标记的默认行为是使用ajax加载目标页面,而不是正常的完整页面加载。 属性rel =“ external”禁用此行为,然后正常地完全加载了引用的页面。 此处的jQM文档中描述了此行为。
注意 :尽管许多答案对帮助我解决此问题做出了具体贡献,但我检查了Mad Man Moon的答案,因为他非常有帮助,并且得分较低。 如果可以检查多个答案,我会做的。
使用attr
代替setAttr
(除非您不使用自定义函数或某些框架/库)
$("#btnEdit").attr( "href", path );
至于自动更改的URL,请查看是否在.htaccess
文件中设置了URL重写,或者是否有可能在其他文件中更改了URL。
即使我注释掉 ,重新启动Web服务器,浏览器会自动在其URL地址字段中的〜/店/店替换〜/店/ 1。 ?!
我必须评论这些说明,重新启动服务器以及避免这种URL替换的方法。
编辑:我决定做我自己的一点测试,并确认问题是您正在设置path = window.location。 设置path = window.location.href ,您的代码将起作用。
尝试这个
var path = window.location;
path = path.replace( "shop","edit" );
$("#btnEdit").prop( "href", path );
您的问题是path
充当window.location
的别名,因此path.replace()
是window.location.replace()
,这会触发重定向。
解决方案:在window.location
的末尾添加.toString()
以获取字符串值而不是对象。 var path = window.location.toString()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.