問題:
您需要修改'rows' URL 參數在給定的URL 中新增特定值,如果不存在則新增預設值。
解決方案:
使用 updateURLParameter 等 JavaScript 函數來操作 URL參數。以下是問題答案中提供的程式碼的擴充版本:
/** * http://stackoverflow.com/a/10997390/11236 */ function updateURLParameter(url, param, paramVal) { let newAdditionalURL = ""; const tempArray = url.split("?"); const baseURL = tempArray[0]; let additionalURL = tempArray[1]; let temp = ""; if (additionalURL) { const additionalURLArray = additionalURL.split("&"); additionalURLArray.forEach((paramValue) => { if (paramValue.split('=')[0] != param) { newAdditionalURL += temp + paramValue; temp = "&"; } }); } const rows_txt = temp + "" + param + "=" + paramVal; return baseURL + "?" + newAdditionalURL + rows_txt; } // Function Calls: const newURL1 = updateURLParameter(window.location.href, 'locId', 'newLoc'); const newURL2 = updateURLParameter(newURL1, 'resId', 'newResId'); window.history.replaceState('', '', updateURLParameter(window.location.href, "param", "value"));
更新版本處理 URL 錨點:
function updateURLParameter(url, param, paramVal) { let TheAnchor = null; let newAdditionalURL = ""; const tempArray = url.split("?"); const baseURL = tempArray[0]; let additionalURL = tempArray[1]; let temp = ""; if (additionalURL) { const tmpAnchor = additionalURL.split("#"); TheParams = tmpAnchor[0]; TheAnchor = tmpAnchor[1]; if (TheAnchor) additionalURL = TheParams; const tempArray = additionalURL.split("&"); tempArray.forEach((paramValue) => { if (paramValue.split('=')[0] != param) { newAdditionalURL += temp + paramValue; temp = "&"; } }); } else { const tmpAnchor = baseURL.split("#"); TheParams = tmpAnchor[0]; TheAnchor = tmpAnchor[1]; if (TheParams) baseURL = TheParams; } if (TheAnchor) paramVal += "#" + TheAnchor; const rows_txt = temp + "" + param + "=" + paramVal; return baseURL + "?" + newAdditionalURL + rows_txt; }
以上是如何使用 JavaScript 修改 URL 參數並指定預設值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!