global variables with jquery mobile multipage
-
31-05-2021 - |
Question
I have a multipage design with jquery mobile. On the first site i call a function with onklick() to fill a global array with values. Now i want to display this values on the second site, but i can't manage to display them with document.write(array)
Solution
To append data to the DOM you first need to select an element to append it to, then in your case iterate through the array, adding each index's value to the DOM:
//here is the array of values
var myArr = [...];
//wait for out page to initialize
$(document).delegate('#my-page-id', 'pageinit', function () {
//create an array to buffer the output
var output = [];
//use a fast loop to add the value at each index to an array,
//in this case I'm adding some HTMl markup to it as well
for (var i = 0, len = myArr.length; i < len; i++) {
output.push('<li>' + myArr[i] + '</li>');
}
//check to see if there were any indexes in the array
if (output.length) {
//append a list-view widget with the info from myArr to the content section of the current page
$(this).children('.ui-content').append('<ul data-role="listview">' + output.join('') + '</ul>').trigger('create');
}
});
Documentation for document.write
: https://developer.mozilla.org/en/document.write
Here is a JSPerf to show the performance difference between some loops: http://jsperf.com/jquery-each-vs-for-loops/2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow