[英]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.