[英]How to access the inner function's variable from outer function with jQuery?
我已經看到了從內部到外部的訪問函數,但是我找不到如何使用JQUERY而不是javaScript從外部函數訪問內部函數的變量的確切答案。
我下面有代碼
$(document).ready(function(){
var outv=1;
function innerfunc(){
var innerfuncv=2;
var outv=3;
alert(outv);
};
alert(outv);
innerfunc();
alert(outv);
alert(innerfunc.outv);
});//$(document).ready(function() END
請幫忙。 謝謝! 讓我知道是否需要更多信息。
在函數外定義它們。 在函數內部定義的變量只能用於該函數,因此,如果要訪問它們,則必須在函數外部定義它們。
$(document).ready(function () {
var outv = 1;
var innerfuncv;
function innerfunc() {
innerfuncv = 2;
outv = 3;
alert(outv);
};
alert(outv);
innerfunc();
alert(outv);
/* alert(innerfunc.outv); this wont work*/
});
AFAIK,您不能這樣做,一種選擇是將上下文包裝在一個對象中:
$(document).ready(function(){
var outv=1;
var inner = {
innerfuncv:2,
outv:3,
innerfunc : function (){
console.log(this.outv);
}
}
console.log(outv);
inner.innerfunc();
console.log(outv);
console.log(inner.outv);
});
$(document).ready(function(){
var outv=1;//you can access this any where within dom ready..
function innerfunc(){
var innerfuncv=2;//this is a local variable and its scope is within function
outv=3;//get rid of var when you have already declared it.
alert(outv);//this will get overWritten..1 is replaced by 3
};
alert(outv);//will alert 1
innerfunc();
alert(outv);//will alert 3,not 1
});//$(document).ready(function() END
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.