此jQuery實用程序功能有效地檢查當前URL中的參數。如果不存在,它將附加參數並返回完整的,更新的URL。這對於AJAX請求更新數據庫並隨後重定向到同一頁面特別有用,但帶有指示成功更新的標誌(例如,顯示確認消息)。
(function($,W,D){ var JQUERY4U = {}; JQUERY4U.UTIL = { /** * Appends a parameter to a URL if it doesn't already exist. * @param {string} param - The parameter name to add. * @param {string} value - The parameter value. * @returns {string} The URL with the appended parameter. */ addParamToUrl: function(param, value){ // Check if parameter exists var regex = new RegExp(param + "=([^&]*)", "i"); var existingParam = regex.exec(W.location.search); var existingValue = existingParam && existingParam[1] || ""; // Construct the URL var loc = W.location; var url = loc.protocol + '//' + loc.host + loc.pathname + loc.search; // Add parameter if it doesn't exist if (existingValue === ''){ url += (loc.search === '' ? '?' : '&') + param + '=' + value; } return url; } }; // Example usage: var newUrl = JQUERY4U.UTIL.addParamToUrl('updated', 'true'); console.log(newUrl); // Input: http://jquery4u.com/index.php // Output: http://jquery4u.com/index.php?updated=true })(jQuery, window, document);
>經常詢問有關jQuery URL參數操縱的問題(常見問題解答) 使用jQuery
添加多個參數
$.param()
var data = { param1: "value1", param2: "value2" }; var url = "http://example.com/page?" + $.param(data);
對象:URL
URLSearchParams
>檢查存在參數存在
let url = new URL("http://example.com/page?param1=value1¶m2=value2"); url.searchParams.delete('param1');
修改參數值URLSearchParams.has()
let url = new URL("http://example.com/page?param1=value1¶m2=value2"); let hasParam1 = url.searchParams.has('param1'); // true
添加參數,沒有頁面重新加載URLSearchParams.set()
let url = new URL("http://example.com/page?param1=value1¶m2=value2"); url.searchParams.set('param1', 'newValue1');
以上是jQuery添加參數到URL功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!