简体   繁体   中英

Accessing javascript array from onclick function

I am using jQuery and populating an array on document.ready.

In my page I have some elements with a click event. I defined that function outside of the document.ready function.

I can't seem to figure out how to access that array variable from within my onclick function.

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. And you need to bind it to the element there instead of inline attribute:

$(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.

 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函数中引用它。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM