我如何在onclick外部访问test2()函数,如普通函数所示,用括号括起来,告诉运行时将函数返回到父作用域,一旦返回该函数,则使用第4行执行通过这些步骤将有所帮助。
<p onclick='test().test2()'> some text </p>;
<script>
//the below declaration will not change
var jQuery = 'Hi';
(function ($) {
function test(){
function test2(){
alert('text')
}
alert($)
}
console.log($);
test().test2()
})(jQuery)
</script>
最佳答案
仅当在与希望访问函数的作用域相同的范围内声明函数时,才能访问test2
。在这种情况下,这意味着您需要在外部范围中声明该函数。
您可以通过在外部作用域中设置一个变量来实现,如下所示:
var test2;
var jQuery = 'Hi';
(function ($) {
function test(){
test2 = function(){
alert('text')
}
alert($)
}
console.log($);
test(); //test needs to be called first to define test2.
test2();
})(jQuery)