现在需要在点击查询按钮,清空,最好可以独立设置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
Manipulating the browser history – Web APIs | MDN
1 2 | var locationHref = window.location.href console.log( "locationHref=%o" , locationHref) |
调试输出:
另外:
1 | window. history .pushState({ "q" : "" }, document.title, "/" + HomePageUrl) |
输出:
1 | 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' . |
【总结】
最后用代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | / / 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) 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中的查询参数