最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】html和js中如何设置或清空url中的查询参数

参数 crifan 3770浏览 0评论
现在需要在点击查询按钮,清空,最好可以独立设置url中的查询参数:
index.html?q=&tag=Individuality&difficulty=7
变成:
index.html?q=
或:
index.html
js clear html url query string
js clean html url query string
javascript – Remove URL parameters without refreshing page – Stack Overflow
Manipulating the browser history – Web APIs | MDN
https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method
Manipulating the browser history – Web APIs | MDN
javascript – Is there any method to get the URL without query string? – Stack Overflow
var locationHref = window.location.href
console.log("locationHref=%o", locationHref)
调试输出:
locationHref="file:///Users/crifan/dev/dev_root/company/xxx/projects/xxx/www/xxxWeb/index.html?q=&tag=Individuality&difficulty=7"
另外:
window.history.pushState({"q": ""}, document.title, "/" + HomePageUrl)
输出:
main.js:18 Uncaught DOMException: Failed to execute 'pushState' on 'History': A history state object with URL 'file:///index.html' cannot be created in a document with origin 'null' and URL 'file:///Users/crifan/dev/dev_root/company/xxx/projects/xxx/www/xxxWeb/index.html?q=&tag=Individuality&difficulty=7'.
Access the browser’s query string as a JavaScript Object
Solved: Remove parameters from URL – Optiverse
Remove Query String with JavaScript and HTML5
remove url parameters with javascript or jquery – Stack Overflow
javascript – How can I remove the query string from the url after the page loads? – Stack Overflow
【总结】
最后用代码:
// from: file:///xxx/xxxWeb/index.html?q=&tag=Individuality&difficulty=7
// got: /xxx/xxxWeb/index.html
function getCurUrlPath(){
  // var curUrl = window.location.href.substring(window.location.href.lastIndexOf('/') + 1).split("?")[0]
  // console.log("curUrl=%o", curUrl)
  // locationHref="file:///xxx/xxxWeb/index.html?q=&tag=Individuality&difficulty=7"
  var locationPathname = window.location.pathname
  console.log("locationPathname=%o", locationPathname)
  return locationPathname
}


// clear query string in url: index.html?q=&tag=Individuality&difficulty=7
// to : index.html
function clearQueryStrInUrl(){
  // var locationHref = window.location.href
  // console.log("locationHref=%s", locationHref)
  var curUrl = getCurUrlPath()
  console.log("curUrl=%s", curUrl)
  var curTitle = document.title
  console.log("curTitle=%s", curTitle)
  // window.history.pushState({"q": ""}, curTitle, curUrl)
  window.history.pushState({}, curTitle, curUrl)
}
即可实现:清除当前页面的url中的查询参数。

转载请注明:在路上 » 【已解决】html和js中如何设置或清空url中的查询参数

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
80 queries in 0.177 seconds, using 22.24MB memory