我正在寻找有关如何禁用将使用 jquery/jquerymobile 重定向到同一页面的链接的最佳实践。
例如,如果我在主页上并且有一个指向主页的链接,它甚至不应该刷新页面。
我的链接代码:
<a href="Homepage.aspx" rel="external">Home</a>
我正在寻找有关如何禁用将使用 jquery/jquerymobile 重定向到同一页面的链接的最佳实践。
例如,如果我在主页上并且有一个指向主页的链接,它甚至不应该刷新页面。
我的链接代码:
<a href="Homepage.aspx" rel="external">Home</a>
完全未经测试,但取决于您的代码是如何编写的,这可能会起作用。
$('a').each(function(){
if($(this).attr('href') === window.location.pathname)
$(this).removeAttr('href');
// Alternatively: $(this).attr('href','#');
});
我对 jquery/jquery mobile 不够熟悉,不知道这是否是最佳实践,但它应该可以工作。
$("a").each(function(){
if(window.location.href==this.href)
this.onclick=function(){return false};
});
您可以使用解析当前 URLwindow.location.href
并提取页面名称。
然后,您可以对每个链接进行迭代,并为具有与当前页面值相同的 href 值的链接附加行为
var currentPage = ....// extract the page from window.location.href
$('a').each(function(index, element) {
var currentA = $(this);
if (currentA.attr('href') == currentPage) {
// Append a listener on the click event that will return false
// and stop the default behaviour
currentA.on('click', false);
}
});
注意:将 false 设置为处理函数与创建返回 false 的匿名函数相同,并且再次与创建调用event.stopPropoagation()
和event.preventDefault()
for (var a = document.getElementsByTagName("A"), b = 0; b < a.length; b++) {
if (a[b].href === window.location.href.split("#")[0] && a[b].hasChildNodes()) {
for (var c = 0; b < a[b].childNodes.length; c++) {
a[b].parentNode.insertBefore(a[b].childNodes[c].cloneNode(!0), a[b]);
}
}
}