我有一個選單,其中的鏈接可能類似??于以下內容之一:
mywebsite.com/#find
mywebsite.com/about-us/#team
mywebsite.com/#social
mywebsite.com/services/#something
我只想對第一個和第三個鏈接(在 url 路徑中沒有子目錄的鏈接)做一些事情。如何檢查 # 哈希是否是鏈接中第一個斜杠之后的第一個元素?
$('#menu a').click(function() {
var target = this.href;
// check if "/#" is the first thing after the domain name
});
謝謝你。
uj5u.com熱心網友回復:
決議 URL的URL類可以幫助你。URL.pathname屬性包含 url 的路徑(域后的字串)
$('#menu a').click(function(e) {
if (new URL(this.href).pathname == "/"){
// Do something
}
});
更準確的模式是
$('#menu a').click(function(e) {
let url = new URL(this.href)
if (url.pathname == "/" && url.hash != ''){
// Do something
}
});
顯示代碼片段
$('#menu a').click(function(e) {
e.preventDefault();
if (new URL(this.href).pathname == "/")
console.log("true");
});
a {display: block}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="menu">
<a href="http://mywebsite.com/#find">mywebsite.com/#find</a>
<a href="http://mywebsite.com/about-us/#team">mywebsite.com/about-us/#team</a>
<a href="http://mywebsite.com/#social">mywebsite.com/#social</a>
<a href="http://mywebsite.com/services/#something">mywebsite.com/services/#something</a>
</div>
uj5u.com熱心網友回復:
讓我們先忽略該https://部分,然后找到第一個/并希望#在它之后找到一個。
var tests = `mywebsite.com/#find
mywebsite.com/about-us/#team
https://mywebsite.com/#social
mywebsite.com/services/#something`.split("\n");
function isMyHash(url) {
var start = url.indexOf("://") > -1 ? url.indexOf("://") 3 : 0;
start = url.indexOf("/", start);
return (url.substring(start 1, start 2) == '#')
}
tests.forEach(function(test) {
console.log(test, isMyHash(test) ? "?" : "x")
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/521764.html
