I have a listview which I created with JavaScript/jQuery. When I click on a listitem I have to execute code.
Scenario 1:
I use this code:
$("div#home ul#one li").live('click', function() { console.log('click') });
this code picks up the click, but it picks it up twice. So when I click on a listitem it outputs two console.logs
Scenario 2:
I have this code for another list which was created in the normal index.html file.
$("div#home ul#two li").off('click').on('click', function() { console.log('click') });
This code doesn’t execute the code twice.
Is there anyway I could get Scenario 2 working on the JavaScript created listview? (Any other suggestions are welcome too)
The problem is that you’re not binding your
onlistener in the right place, you are declaring in apageinithandler for ANY page to add youronlistener to the li:$("div#home").on('click','li', function() { console.log('click') });Thus you are attaching one listener on the
div#loginpage and attaching a redundant 2nd listener on the seconddiv#homepage. When you click thelione event is fired to two listeners and you get the two clicks.What you should be doing is in your
$(document).on('pageinit', function()wrap your on listener declaration in a conditional that checks which page you’re on:That’s the simple solution, what you really should be doing is branching your code based on which page fired the
pageinitevent and calling the correct code based on it. See: my guide on structuring jQM Apps.The gist of it is attach a data attr to your
div[data-role=page]etc that describes your page then call separate code for each page. (instead of using the ID like in this example, because you can easily have more than one instance of a page in multi-page jQM apps)