![](/img/trans.png)
[英]How to make a nav bar in a single php page with mouseovers and current page images?
[英]How to match current page url with nav bar?
我需要將導航到的頁面的URL與導航欄(使用jQuery)中的li元素進行比較。
到目前為止,我已經將當前網址分配給了一個變量,就像這樣
var currentPage = window.location.href;
然后我有一個.each
函數,檢查導航欄中的每個項目,像這樣
$("nav ul li a").each(
function() {
}
);
現在,我假設我需要在函數內部使用某種if語句,也許是這樣的?
if(currentPage === ????) {};
我不知道是什么比較列表中的url?
基本上,我想在導航欄中突出顯示我正在瀏覽的任何頁面。 一旦我弄清楚如何讓jQuery確認我在哪個頁面上並將其與導航欄匹配,我將使用.css更改背景圖像,以使我站在導航欄上的哪個頁面脫穎而出。 我在jQuery類中,這已分配。
我在這里四處搜尋,但找不到我要嘗試的真正匹配的東西。
希望有人能提供一些見識...如果這個問題甚至有意義,我實際上是在拔頭發,只是想將其表達為一個問題,更不用說弄清楚了...
我認為您可能正在尋找:
this.href
那應該給您您正在循環的標簽的實際href。
(答案有所改善,感謝以下評論)
您可以使用parse(..)來匹配鏈接是否為當前頁面。該演示無法在stackoverflow中正確運行,如果要查看結果,則應轉到codepen 。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <style> a { color: #000; } a.active { color: red; } </style> <nav> <ul> <li><a href="?home">Home</a></li> <li><a href="?contact">Contact</a></li> <li><a href="?about">About</a></li> <li><a href="?contact#hash">Contact Us</a></li> </ul> </nav> <script> function parse(url) { var parts = url.match(/^([^#?]*?)?(\\?.*?)?(#.*)?$/); return { uri: parts[1], search: parts[2], hash: parts[3], /** * * @param that <b>string</b>/<b>object</b> has `href` property,eg:location * @param hash skip hash matching * @param search skip search matching * @returns {boolean|*} if url matched return `true`,otherwise return `false`. */ match: function (that, hash, search) { var self = this, that = parse(typeof that == 'string' ? that : that.href); return (!self.uri || self.uri == that.uri) && (search || self.search == that.search) && (hash || self.hash == that.hash); } }; } $('nav li a').each(function () { console.log(['matching with ', this.href, '===>', parse(this.href).match(location)].join(' ')); console.log(['matching with ', $(this).attr('href'), '===>', parse($(this).attr('href')).match(location)].join(' ')); if (parse($(this).attr('href')).match(location/*,true*/))//remove comment and try the result. $(this).addClass('active'); }); </script>
對於任何看這個的人,我都知道使用this和.each。 這是它的樣子。
var currentPage = window.location.href;
$("nav ul li a").each(
function() {
console.log($(this).attr("href"));
if (currentPage.indexOf($(this).attr("href")) !== -1){
$(this).addClass("highlight");
return false;
}
}
);
當我第一次嘗試解決這個問題時,我還很遙遠,我想我誤解了我的老師,並且正在思考這個問題。 無論如何,這很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.