我需要根据单击的div的ID从URL动态删除id
参数。 id用大写字母Z隔开。我基本上需要写一张与单击的div的id
与URL中的id
匹配的支票。然后,如果单击该参数,则将其删除,并使用已删除的id
的URL重新加载页面。
通常,如果只有一个id
可用,我已经写了一些JQuery将其删除。
以下是示例网址
http://example.com/cyegyufy-Z9c86uh9ozzpZ90a9emsjmdiZgjkgkjgkukZlkhlkhlklk
import * as $ from 'jquery';
$('blah blah blah'). on('click', e=> {
removeParam(e)
console.log('has been clicked')
})
const removeParam =(e) => {
var pathArray = window.location.href.split('-Z');
var ArticlePillId = e.currentTarget.id
if (pathArray[1] === ArticlePillId) {
pathArray.splice(1)
}
console.log(pathArray)
window.location.href = pathArray[0]
}
这将使用正确的URL重新加载页面,但它是静态的。
答案 0 :(得分:0)
您可以根据文章上的点击事件动态调整URL的路径名。请注意,通过在window.location
中分配/更改任何内容,页面将自动重新加载。
document.querySelectorAll("article").forEach(article => {
article.addEventListener("click", function() {
let url = window.location,
path = url.pathname,
articleID = article.id,
articlePill = "-Z" + articleID,
articleRE = /-Z(\w+)/g,
articles = path.match(articleRE);
if (!articles) articles = [];
if (articles.includes(articlePill)) {
articles = articles.filter(article => article != articlePill);
} else {
articles.push(articlePill);
}
url.pathname = articles.join("");
});
});
let url = new URL("http://www.example.com/cyegyufy-ZfirstArticle-ZsecondArticle");
// window.location.pathname
document.querySelectorAll("article").forEach(article => {
article.addEventListener("click", function() {
let path = url.pathname,
articleID = article.id,
articlePill = "-Z" + articleID,
articleRE = /-Z(\w+)/g,
articles = path.match(articleRE);
if (!articles) articles = [];
if (articles.includes(articlePill)) {
articles = articles.filter(article => article != articlePill);
} else {
articles.push(articlePill);
}
url.pathname = articles.join("");
console.log(url);
});
});
article {
height: 100px;
margin: 5px;
width: 100px;
border: 1px solid black;
}
<article id="firstArticle">
<h6>firstArticle</h6>
</article>
<article id="secondArticle">
<h6>secondArticle</h6>
</article>