📜  获取参数 js - Javascript (1)

📅  最后修改于: 2023-12-03 14:57:13.980000             🧑  作者: Mango

获取参数

在JavaScript中,我们可以通过不同的方式获取参数:

1. 通过URL参数获取

我们可以通过解析URL,获取URL中的参数,实例如下:

// 获取URL中的参数
function getParameterByName(name) {
  name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
  return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

// 触发获取参数
var param1 = getParameterByName('param1');
var param2 = getParameterByName('param2');

// 输出参数
console.log(param1);
console.log(param2);
2. 通过表单获取

我们可以在HTML中通过表单获取参数,实例如下:

<form>
  <label for="param1">Param 1:</label>
  <input type="text" id="param1" name="param1">

  <label for="param2">Param 2:</label>
  <input type="text" id="param2" name="param2">

  <button type="submit">Submit</button>
</form>
// 获取表单中的参数
var form = document.querySelector('form');
var param1 = form.elements.param1.value;
var param2 = form.elements.param2.value;

// 输出参数
console.log(param1);
console.log(param2);
3. 通过事件获取

我们可以在JavaScript中监听事件,获取事件的参数,实例如下:

<button onclick="getParams('param1', 'param2')">Get Params</button>
// 获取事件中的参数
function getParams(param1, param2) {
  // 输出参数
  console.log(param1);
  console.log(param2);
}

以上三种方式都可以获取JavaScript中的参数,我们应该根据具体场景选择合适的方式。