javascript - elements are not defined at the time the script is executed -


i'm trying data attribute of elements, when object created, elements aren't loaded yet (which understand). question best (or any) solution need use object in 2 separate functions don't interact each other?

function data_num_array(){     this.data_num_array=$("*[data-num]"); }  data_num_array.prototype.get_data_num_array_element=function(string_val){     var data_num_of_element;     for(var i=0;i<this.data_num_array.length;i++){         if(this.data_num_array[i].id===string_val){             data_num_of_element=$(this.data_num_array[i]).attr("data-num");             break;         }     }     return data_num_of_element; };  function call_me(){     console.log(obj.get_data_num_array_element("div")); } 

if there's syntax error here it's not issue, case of question.

var obj=new data_num_array();  $(document).ready(function(){     console.log(obj.get_data_num_array_element("div")); });  $("#click").click(function(){     console.log(obj.get_data_num_array_element("click")); });  <html>     <head>     </head>     <body>         <div id="div" data-num="1"></div>         <button id="click" data-num="2"></button>     </body> </html> 

if you're new javascript, might worth reading on scoping: mdn: variable scoping

in short, obj needed across 2 functions, can leverage scoping ensure both $(document).ready , $("#click") have access obj. obj, on other hand, needs wait until document ready. can hold off on instantiating data_num_array $(document).ready callback function you're using.

with bit of rearranging:

function data_num_array(){     this.data_num_array=$("*[data-num]"); }  data_num_array.prototype.get_data_num_array_element=function(string_val){     var data_num_of_element;     for(var i=0;i<this.data_num_array.length;i++){         if(this.data_num_array[i].id===string_val){             data_num_of_element=$(this.data_num_array[i]).attr("data-num");             break;         }     }     return data_num_of_element; };  $(document).ready(function(){   var obj=new data_num_array();    console.log(obj.get_data_num_array_element("div"));    $("#click").click(function(){     console.log(obj.get_data_num_array_element("click"));   }); }); 

now, we're waiting set new data_num_array , click event.

also, had small bug in click handler calling obj.get_data_num_array_element("button") instead of obj.get_data_num_array_element("click"). (you gave <button> id of "click".)

on more opinionated side, consider using camelcase variable names. less characters type. ;)


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -