take a look at this fiddle here.
If you click the black diagonal line(as indicated by the message in red letters) the content below changes. The new content presented to the user is based into an array filled with values in line 8(a for loop…the content presented )…it is simply values gathered from the data attribute of the HTML.
Suppose now the user clicks again the back diagonal line…an error is produced cause the html has changed(the one appeared in the loop)…what can I do in such a case.
Surely I can find something my own but I want to listen some solution also from others…
There is no black diagonal line above, as the image failed to load.
However, I can use developer tools to simulate the problem, and I can tell why it’s happening.
The first time through, the following element exists.
It will allow the data-value information to be safely stored in an array, and later on after you’ve replaced the show_price elements with other content, you can still refer to that data-value information from the array.
You create the array on each click event, which is the wrong time to do it.
Instead, you want to create the array when the page loads, and populate the array with useful info then too.
That way when the click event occurs, you can retrieve useful info from that array whenever you need it.
yes…what you suggested is the way to go…nonetheless I would appreciate if you could tell me why the declaration inside the handler is wrong…I cannot quite understand it yet.
Is it maybe cause the data on indices is live,if the declaration is made on global scope?
It’s because whenever the click event occurs, the code creates a new array, which isn’t all that useful.
More useful, is to initialise the array outside of the click event, which can be a global variable.
More useful than that, is to place the array and event handler in an IIFE (immediately invoked function expression) which helps to protect the global namespace from global variables.
When the event handler is defined from within the same scope as that of the array, it can access that array without trouble too.