search
HomeWeb Front-endJS TutorialHow to pass parameters in javascript
How to pass parameters in javascriptJun 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>
This method is generally used with ajax, and the above value uses a template Engine

2.window['data']

window["name"] = "the window object";
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 <p>2. Regular expression method</p><pre class="brush:php;toolbar:false">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>test1</button>

<!--高级-->
<button>
  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>点击</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 <h2 id="HTML-data-Custom-attribute">6.HTML5 data-* Custom attribute</h2><pre class="brush:php;toolbar:false"><button>点击</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>点击</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 = """; // 双引号的超文本标记语言

    var params = """ + name + "","" + age + "","" + home + "","" + friend + """;
    var params2 = DQ + name + DQ + ',' + DQ + age + DQ + ',' + DQ + home + DQ + ',' + DQ + friend + DQ;
    var box = document.createElement("p");
    box.innerHTML = "<button>点击</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 点击";
}
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>
  分配
</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 <p> Chestnut: </p><pre class="brush:php;toolbar:false">
  

         <input>   

  

            

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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

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 Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.