我正在尋找關於如何禁用將使用jquery/jquerymobile重定向到相同頁面的鏈接的最佳做法。禁用指向同一頁的鏈接
例如,如果我在hompepage上,並且有指向主頁的鏈接,它甚至不應刷新頁面。
我的鏈接代碼:
<a href="Homepage.aspx" rel="external">Home</a>
我正在尋找關於如何禁用將使用jquery/jquerymobile重定向到相同頁面的鏈接的最佳做法。禁用指向同一頁的鏈接
例如,如果我在hompepage上,並且有指向主頁的鏈接,它甚至不應刷新頁面。
我的鏈接代碼:
<a href="Homepage.aspx" rel="external">Home</a>
我不使用jQuery/jQuery Mobile的不夠熟悉,知道這是一個最好的做法,但它應該工作。
$("a").each(function(){
if(window.location.href==this.href)
this.onclick=function(){return false};
});
完全未經測試,但根據您的代碼是如何編寫這可能是工作。
$('a').each(function(){
if($(this).attr('href') === window.location.pathname)
$(this).removeAttr('href');
// Alternatively: $(this).attr('href','#');
});
這幾乎是做了工作的功能,但我的鏈接,這是一個導航欄按鈕,保持單擊向下風格被點擊之後。 它應該是一個正常的鏈接工作。 – Distwo
您可以用window.location.href
解析當前URL並提取頁面名稱。
然後,您可以遍歷各個環節和追加行爲鏈接具有相同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,並再次與創建調用event.stopPropoagation()
和event.preventDefault()
+1。 – Distwo
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]);
}
}
}
它按預期完成工作! – Distwo
很高興爲您服務! –