[英]Add parameters on href url with javascript and with specific conditions
我的javascript
函数有问题。 我想添加一些参数到href
URL。 例如,当我单击它时,我想在href
URL中添加?param=1
。 但是在添加一些参数之前,我想检查href
的url是否为http://example.com且该参数不包含?param=1
。 检查后,URL为http://example.com并且不包含?param=1
,我想在该URL中添加?param=1
。 为什么要在添加参数之前先检查? 这是因为我不想在任何URL中添加参数,而只是在我想要的特定URL中添加参数。
这是我到目前为止所做的:
window.addEventListener("click", function(e) {
var href = e.target.getAttribute("href");
if(href) {
location.href = href + "?param=1";
e.preventDefault();
}
});
但是,如果href
为http://example.com ,我不知道如何检查并制定具体条件。 请任何人知道如何做到这一点对我有帮助。 之前谢谢。
检查queryString并查看它是否具有param1
值,如果没有,则附加它。
var url = new URL("http://www.example.com?param=1"); //window.location.href
if (url.searchParams.get('param'))
{
console.log("Param exists");
}
else
{
console.log("Param does not exist")
url + "?param=1"
console.log(url);
}
window.addEventListener("click", function(e) { e.preventDefault(); var href = e.target.getAttribute("href"); console.log(href); if(href) { if(href.indexOf("param=1")==-1){ href = href + "?param=1"; console.log(href); // location.href = href; }else{ href = href + "?param=2"; console.log(href); // location.href = href; } // } });
<a href="http:example.com?param=1">click</a>
在字符串或对象中开始搜索的索引。 如果找不到搜索,它将返回-1。
$(document).ready(function(){ var href = "www.example.com?param=1"; if(href.indexOf("www.example.com") >=0 && href.indexOf("param=1") >= 0) { alert('Url has given words'); //location.href = href + "?param=1"; // e.preventDefault(); } })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div>Check URL</div>
看看这个:
window.addEventListener("click", function(e) { const href = e.target.getAttribute("href"); if(href) { console.log(href.includes('?param=1')); // You can do whatever you want based on this condition e.preventDefault(); } });
<a href='http://example.com/'>Link 1</a> <br/><br/> <a href='http://example.com/?param=1'>Link 2</a>
了解有关indexOf的信息,以检查查询字符串中是否存在值
var str="Hello world!" document.write(str.indexOf("Hello") + "<br />") document.write(str.indexOf("World") + "<br />") document.write(str.indexOf("world"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.