如果单击按钮,我想设置var索引。但是我也想在函数2中使用var索引。有没有办法在不使用全局(例如使用 return(的情况下做到这一点?
.HTML:
<button id="edit" onclick="editBox()">Bearbeiten</button>
.JS:
function editBox() {
var index = $(event.target).parent().attr("id");
}
function function2() {
//some code...
}
你的意思是这样的:
function editBox() {
var index = $(event.target).parent().attr("id");
function2(index);
}
function function2(r) {
//some code ( r is id now)
}
您应该首先定义一个超出函数范围的变量,然后调用/分配它。
这里有一个工作片段。
let value;
function func1(id) {
value = id;
console.log('clicked', id);
}
function func2() {
alert(value);
}
<button id="btn" onclick="func1(this.id)">
Click me and get the id
</button>
<button id="btn2" onclick="func2()">
Call second function
</button>
如果在函数内部声明变量,则其作用域仅限于该函数,并且无法从函数外部访问其值。
来自w3schools:
局部变量具有函数作用域:它们只能从函数内部访问。
若要在第二个函数中访问相同的变量,必须在两个函数外部使用var
关键字声明该变量。例如:
var index;
function editBox() {
index = $(event.target).parent().attr("id");
}
function function2() {
console.log(index);
}
唯一的另一种可能性是将变量index
传递给function2()
作为参数,但这只有在从editBox()
内部调用function2()
时才有效。
简短的回答:index
需要存在于比编辑框范围更大的范围内。
您不想要全局变量,因此可以创建"闭包"。在Javascript中,你可以使用IFFE(立即调用的函数表达式(来做到这一点。通过这种方式,许多函数和其他代码段共享相同的作用域,但它仍然是"本地"的,而不是全局的。
(function(){
var index;
$('#edit').on('click', function editBox(event) {
index = $(event.target).parent().attr("id");
});
function function2() {
// some code
console.log(index);
}
// Other code that can call function2 and use index variable...
})();
<button id="edit">Bearbeiten</button>