[英]Accessing javascript array from onclick function
I am using jQuery and populating an array on document.ready. 我正在使用jQuery并在document.ready上填充数组。
In my page I have some elements with a click event. 在我的页面中,我有一些带有click事件的元素。 I defined that function outside of the document.ready function.
我在document.ready函数之外定义了该函数。
I can't seem to figure out how to access that array variable from within my onclick function. 我似乎无法弄清楚如何从我的onclick函数中访问该数组变量。
To simplify, I would like something like this to work: 为简化起见,我希望这样的工作:
$(document).ready(function(){
var artists = new Array();
artists.push('item1');
artists.push('item2');
});
function clickLink() {
alert(artists[0]);
}
Many ways, one of the easiest, move your click hander inside the .ready() function. 最简单的方法之一是在.ready()函数内部移动点击处理程序。 And you need to bind it to the element there instead of inline attribute:
并且您需要将其绑定到那里的元素,而不是inline属性:
$(document).ready(function(){
var artists = new Array();
artists.push('item1');
artists.push('item2');
$('#idOfTheElement').click(function() {
alert(artists[0]);
});
});
hi you lost scope of creation of array, so there is two ways to solve it 您好,您失去了数组创建的范围,因此有两种解决方法
Put all in same scope: 将所有内容置于同一范围内:
$(document).ready(function(){
var artists = new Array();
artists.push('item1');
artists.push('item2');
function clickLink() {
alert(artists[0]);
}
});
Declare array as global: 将数组声明为全局数组:
var artists = new Array();
$(document).ready(function(){
artists.push('item1');
artists.push('item2');
});
function clickLink() {
alert(artists[0]);
}
You have to declare the artists
array outside the document.ready()
function and bind the function with the click event. 您必须在
document.ready()
函数外部声明artists
数组,并将该函数与click事件绑定。
var artists = new Array(); $(document).ready(function() { artists.push('item1'); artists.push('item2'); }); $('button').click(function() { console.log(artists[0]); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>click</button>
一个简单的解决方案是在声明数组变量时删除var关键字,这将使变量变为全局变量,不建议这样做,另一种解决方案是在函数外部声明数组,以便可以从onclick函数中引用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.