Table of Contents
1. Implicit creation of html tags
2.window['data']
3. Use localStorage, cookie, etc. to store
4. Get address bar method
5. Tag binding function parameter passing
this extension
event
6.HTML5 data-* Custom attribute
7. String parameter passing
Single parameter
Multi-parameter passing
Complex parameter passing
8.arguments
9.form form
10. Publish and subscribe to handle complex logic parameter transfer
Home Web Front-end JS Tutorial How to pass parameters in javascript

How to pass parameters in javascript

Jun 27, 2021 am 10:26 AM
javascript

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}}">
Copy after login
This method is generally used with ajax, and the above value uses a template Engine

2.window['data']

window["name"] = "the window object";
Copy after login
window.localStorage.setItem("name", "xiaoyueyue");
window.localStorage.getItem("name");
Copy after login
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"}
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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>
Copy after login

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 +
      " !"
  );
}
Copy after login
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;
  },
Copy after login

6.HTML5 data-* Custom attribute

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

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);
}
Copy after login

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 + "岁了!")
Copy after login

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 + " 是我的好朋友");
}
Copy after login

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>
Copy after login
function fenpei() {
  var args = Array.prototype.slice.call(arguments);
  alert("我是" + args[2] + "油品,数量为 " + args[1] + " 吨, id为 " + args[0]);
}
Copy after login

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("&");
}
Copy after login

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>
Copy after login
document.querySelector("button").onclick = function() {
  console.log("param: " + serialize(document.getElementById("formData"))); // param: ordersaleCode=&extractType=0
};
Copy after login

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
  };
})();
Copy after login

Example used in WeChat applet:

  • global mount use
// app.js
App({
  onLaunch: function(e) {
    // 注册 storage,这是第二条
    wx.Storage = Storage;
    // 注册发布订阅模式
    wx.yue = Event;
  }
});
Copy after login
  • 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");
}
Copy after login
// 传递地址页面获取好数据传递
wx.yue.pub("addAddress", data.info);
// 补充跳转返回
Copy after login
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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles