Home >Web Front-end >JS Tutorial >How to pass parameters in javascript

How to pass parameters in javascript

藏色散人
藏色散人Original
2021-06-27 10:26:326537browse

How to pass parameters in javascript: first create a corresponding js file; then pass the parameters through "function alertInfo(name, age, home, friend) {...}".

How to pass parameters in javascript

The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.

How to pass parameters in javascript?

Summary of JS parameter passing skills

1. Implicit creation of html tags

<input type="hidden" name="tc_id" value="{{tc_id}}">
This method is generally used with ajax, and the above value uses a template Engine

2.window['data']

window["name"] = "the window object";

3. Use localStorage, cookie, etc. to store

window.localStorage.setItem("name", "xiaoyueyue");
window.localStorage.getItem("name");
Features: cookie, localStorage, sessionStorage, indexDB
Features cookie localStorage sessionStorage indexDB
Data life cycle Generally generated by the server, the expiration time can be set It will always exist unless it is cleared Clear when the page is closed Always exists unless cleared
Data storage size 4K 5M 5M Unlimited
Communicate with the server It will be carried in the header every time, and it will affect the request performance Does not participate Do not participate Do not participate

As you can see from the above table, cookie is no longer recommended for storage. If there are no large data storage requirements, you can use localStorage and sessionStorage. For data that does not change much, try to use localStorage to store it, otherwise you can use sessionStorage to store it.

Note: To store object type data, this deep copy method will ignore functions and undefined
var obj = {
  type: undefined,
  text: "xiaoyueyue",
  methord: function() {
    alert("I am an methord");
  }
};

localStorage.setItem("data", JSON.stringify(obj));
console.log(JSON.parse(localStorage.getItem("data"))); // {text: "xiaoyueyue"}

4. Get address bar method

  1. My own encapsulated method
function parseParam(url) {
  var paramArr = decodeURI(url)
      .split("?")[1]
      .split("&"),
    obj = {};
  for (var i = 0; i < paramArr.length; i++) {
    var item = paramArr[i];
    if (item.indexOf("=") != -1) {
      var tmp = item.split("=");
      obj[tmp[0]] = tmp[1];
    } else {
      obj[item] = true;
    }
  }
  return obj;
}

2. Regular expression method

function GetQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

5. Tag binding function parameter passing

<!--base-->
<button id="test1" onclick="alert(id)">test1</button>

<!--高级-->
<button
  id="test"
  name="123"
  yue="xiaoyueyue"
  friend="heizi"
  onclick="console.log(this.getAttribute(&#39;yue&#39;),this.getAttribute(&#39;friend&#39;))"
>
  test
</button>

this extension

Use this to pass parameters. I figured it out while using art-template. It is no longer necessary to pass only one id and splice it into several parameters! happy!

var box = document.createElement("p");
box.innerHTML =
  "<button id=&#39;1&#39; data-name=&#39;xiaoyueyue&#39; data-age=&#39;25&#39; data-friend=&#39;heizi&#39; onclick=&#39;alertInfo(this.dataset)&#39;>点击</button>";
document.body.appendChild(box);

// name,age,friend
function alertInfo(data) {
  alert(
    "大家好,我是" +
      data.name +
      ", 我今年" +
      data.age +
      "岁了,我的好朋友是" +
      data.friend +
      " !"
  );
}
One thing to note here: the stored data—words containing uppercase => will be uniformly converted to lowercase, for example: data-orderId = “2a34fb64a13211e8a0f00050568b2fdd”, when the actual value is this .dataset.orderid;

event

Since this can be used, the event.target method is also available in the event:

Get the current index value according to the class. The parameter can be the event object
  var getIndexByClass =  function (param) {
    var element = param.classname ? param : param.target;
    var className = element.classname;
    var domArr = Array.prototype.slice.call(document.querySelectorAll('.' + className));
    for (var index = 0; index < domArr.length; index++) {
      if (domArr[index] === element) {
        return index;
      }
    }
    return -1;
  },

6.HTML5 data-* Custom attribute

<button data-name="xiaoyueyue">点击</button>
var btn = document.querySelector("button");
btn.onclick = function() {
  alert(this.dataset.name);
};

7. String parameter passing

Single parameter

var name = "xiaoyueyue",
  age = 25;

var box = document.createElement("p");
box.innerHTML = "<button onclick=\"alertInfo(&#39;" + name + "&#39;)\">点击</button>";
document.body.appendChild(box);

// name, age
function alertInfo(name, age, home, friend) {
  alert("我是" + name);
}

Multi-parameter passing

  var name = 'xiaoyueyue',
      age = '25',
      home = 'shanxi',
      friend = 'heizi',
      DQ = "&quot;"; // 双引号的超文本标记语言

    var params = "&quot;" + name + "&quot;,&quot;" + age + "&quot;,&quot;" + home + "&quot;,&quot;" + friend + "&quot;";
    var params2 = DQ + name + DQ + ',' + DQ + age + DQ + ',' + DQ + home + DQ + ',' + DQ + friend + DQ;
    var box = document.createElement("p");
    box.innerHTML = "<button onclick=&#39;alertInfo(" + params + ")&#39;>点击</button>";
    console.log(box)
    document.body.appendChild(box);


    // name, age,home,friend
    function alertInfo(name, age, home, friend) {
      alert("我是" + name + ',' + "我今年" + age + "岁了!")

Complex parameter passing

var data = [
  {
    name: "xiaoyueyue",
    age: "25",
    home: "shanxi",
    friend: "heizi"
  }
];

var box = document.createElement("p"),
  html = "";

for (var i = 0; i < data.length; i++) {
  html +=
    "<button id=&#39;btn&#39;  onclick=&#39;alertInfo(id,\"" +
    data[i].name +
    &#39;","&#39; +
    data[i].age +
    &#39;","&#39; +
    data[i].home +
    &#39;","&#39; +
    data[i].friend +
    "\")&#39;>点击</button>";
}
box.innerHTML = html;
document.body.appendChild(box);

function alertInfo(id, name, age, home, friend) {
  alert("我是 " + name + " , " + friend + " 是我的好朋友");
}

8.arguments

argumentsThe object is all (non-arrow) Local variables available in functions. You can reference a function's parameters within a function using the arguments object. It is an array-like object.

[Recommended learning: javascript advanced tutorial]

<button
  onclick="fenpei(&#39;f233c7a290ae11e8a0f00050568b2fdd&#39;,&#39;100&#39;,&#39;0号 车用柴油(Ⅴ)&#39;)"
>
  分配
</button>
function fenpei() {
  var args = Array.prototype.slice.call(arguments);
  alert("我是" + args[2] + "油品,数量为 " + args[1] + " 吨, id为 " + args[0]);
}

9.form form

With the help of form form, ajax transfers the sequence Parameterization

// form表单序列化,摘自JS高程
function serialize(form) {
  var parts = [],
    field = null,
    i,
    len,
    j,
    optLen,
    option,
    optValue;

  for (i = 0, len = form.elements.length; i < len; i++) {
    field = form.elements[i];

    switch (field.type) {
      case "select-one":
      case "select-multiple":
        if (field.name.length) {
          for (j = 0, optLen = field.options.length; j < optLen; j++) {
            option = field.options[j];
            if (option.selected) {
              optValue = "";
              if (option.hasAttribute) {
                optValue = option.hasAttribute("value")
                  ? option.value
                  : option.text;
              } else {
                optValue = option.attributes["value"].specified
                  ? option.value
                  : option.text;
              }
              parts.push(
                encodeURIComponent(field.name) +
                  "=" +
                  encodeURIComponent(optValue)
              );
            }
          }
        }
        break;

      case undefined: //fieldset
      case "file": //file input
      case "submit": //submit button
      case "reset": //reset button
      case "button": //custom button
        break;

      case "radio": //radio button
      case "checkbox": //checkbox
        if (!field.checked) {
          break;
        }
      /* falls through */

      default:
        //don&#39;t include form fields without names
        if (field.name.length) {
          parts.push(
            encodeURIComponent(field.name) +
              "=" +
              encodeURIComponent(field.value)
          );
        }
    }
  }
  return parts.join("&");
}

Chestnut:

<form id="formData">
  <p class="pop-info">
    <label for="ordersaleCode">订单编号:</label>
    <input
      type="text"
      id="ordersaleCode"
      name="ordersaleCode"
      placeholder="请输入订单编号"
    />
  </p>
  <p class="pop-info">
    <label for="extractType">配送方式:</label>
    <select id="extractType" name="extractType" class="mySelect">
      <option value="0" selected>配送</option>
      <option value="1">自提</option>
    </select>
  </p>
</form>
<button>获取参数</button>
document.querySelector("button").onclick = function() {
  console.log("param: " + serialize(document.getElementById("formData"))); // param: ordersaleCode=&extractType=0
};

10. Publish and subscribe to handle complex logic parameter transfer

Supports first subscribe and then publish, and first publish and then subscribe
  • Method source code
var Event = (function() {
  var clientList = {},
    pub,
    sub,
    remove;

  var cached = {};

  sub = function(key, fn) {
    if (!clientList[key]) {
      clientList[key] = [];
    }
    // 使用缓存执行的订阅不用多次调用执行
    cached[key + "time"] == undefined ? clientList[key].push(fn) : "";
    if (cached[key] instanceof Array && cached[key].length > 0) {
      //说明有缓存的 可以执行
      fn.apply(null, cached[key]);
      cached[key + "time"] = 1;
    }
  };
  pub = function() {
    var key = Array.prototype.shift.call(arguments),
      fns = clientList[key];
    if (!fns || fns.length === 0) {
      //初始默认缓存
      cached[key] = Array.prototype.slice.call(arguments, 0);
      return false;
    }

    for (var i = 0, fn; (fn = fns[i++]); ) {
      // 再次发布更新缓存中的 data 参数
      cached[key + "time"] != undefined
        ? (cached[key] = Array.prototype.slice.call(arguments, 0))
        : "";
      fn.apply(this, arguments);
    }
  };
  remove = function(key, fn) {
    var fns = clientList[key];
    // 缓存订阅一并删除
    var cachedFn = cached[key];
    if (!fns && !cachedFn) {
      return false;
    }
    if (!fn) {
      fns && (fns.length = 0);
      cachedFn && (cachedFn.length = 0);
    } else {
      if (cachedFn) {
        for (var m = cachedFn.length - 1; m >= 0; m--) {
          var _fn_temp = cachedFn[m];
          if (_fn_temp === fn) {
            cachedFn.splice(m, 1);
          }
        }
      }
      for (var n = fns.length - 1; n >= 0; n--) {
        var _fn = fns[n];
        if (_fn === fn) {
          fns.splice(n, 1);
        }
      }
    }
  };
  return {
    pub: pub,
    sub: sub,
    remove: remove
  };
})();

Example used in WeChat applet:

  • global mount use
// app.js
App({
  onLaunch: function(e) {
    // 注册 storage,这是第二条
    wx.Storage = Storage;
    // 注册发布订阅模式
    wx.yue = Event;
  }
});
  • Usage example
// 添加收货地址页面订阅
 onLoad: function (options) {
        wx.yue.sub("addAddress", function (data) {
            y.setData({
                addAddress: data
            })
        })
 }
/**
 * 生命周期函数--监听页面隐藏
 */
 onHide: function () {
    // 取消多余的事件订阅
    wx.Storage.removeItem("addAddress");
},
 onUnload: function () {
    // 取消多余的事件订阅
    wx.yue.remove("addAddress");
}
// 传递地址页面获取好数据传递
wx.yue.pub("addAddress", data.info);
// 补充跳转返回
Note: Pay attention to uninstalling the data after using it, and operate when the page is closed

The above is the detailed content of How to pass parameters in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn