I don't know if my question is right as in the title. generally, I have this code:
function one(){ var main= document.getElementById('main'); var arr = ['a','b','c','d','e']; var btn = document.createEement('button'); var btnTxt= document.createTextNode('click'); main.appendChild(btn); btn.appendChild(btnTxt); btn.setAttribute('onclick','two()'); return arr; } function two() { //I need to get the arr variable here. }
Set a variable equal to the function.
var oneResult = one();
function one(){ var main= document.getElementById('main'); var arr = ['a','b','c','d','e']; var btn = document.createElement('button'); var btnTxt= document.createTextNode('click'); main.appendChild(btn); btn.appendChild(btnTxt); btn.setAttribute('onclick','two()'); return arr; } function two(){ // i need to get the arr varible here. var oneResult = one(); } two();
<div id="main"></div>
One possible solution is to pass arr
as argument of function two
using JSON.stringify() and template literals . Note if you call one()
inside function two()
a new button will be created every time:
function one() { var main = document.getElementById('main'); var arr = ['a','b','c','d','e']; var btn = document.createElement('button'); var btnTxt= document.createTextNode('click'); main.appendChild(btn); btn.appendChild(btnTxt); btn.setAttribute('onclick',`two(${JSON.stringify(arr)})`); return arr; } function two(arr) { //I need to get the arr variable here. console.log(arr); } one();
<div id="main"></div>
call the one function in two
function one(){ var main= document.getElementById('main'); var arr = ['a','b','c','d','e']; var btn = document.createEement('button'); var btnTxt= document.createTextNode('click'); main.appendChild(btn); btn.appendChild(btnTxt); btn.setAttribute('onclick','two()'); return arr; } function two(){ var v=one(); // i need to get the arr varible here. }
Just call the function one()
in two because its return
the arr
.Also you don't have div with id = main
so I added it
Note : The function one()
will be called on each click of btn
so new btns
will be created
function one(){ var main= document.getElementById('main'); var arr = ['a','b','c','d','e']; var btn = document.createElement('button'); var btnTxt= document.createTextNode('click'); main.appendChild(btn); btn.appendChild(btnTxt); btn.setAttribute('onclick','two()'); return arr; } one(); function two(){ var arr = one(); console.log(arr); // i need to get the arr varible here. }
<div id="main"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.