Dynamic selector
Page 1 of 1
Interinactive
VIP Member



Posts: 29466

PostPosted: Tue, 24th Mar 2015 07:22    Post subject: Dynamic selector
Is there any reason this shouldn't work?

Code:
      var question = 1;
      $("ul#question"+question+" li").on( "click", function(e) {
         dowhatever();
         question++;
      });


The selector doesn't seem to work after the first time, despite the fact that I can see the change in the console
Back to top
PumpAction
[Schmadmin]



Posts: 26759

PostPosted: Tue, 24th Mar 2015 09:10    Post subject:
what about giving them a class and doing the following
var $questions = $('.question');

$questions.on('click', function (e) {
console.log('You clicked on question:' + $questions.index(e.target)+1);

});


=> NFOrce GIF plugin <= - Ryzen 3800X, 16GB DDR4-3200, Sapphire 5700XT Pulse
Back to top
shole




Posts: 3363

PostPosted: Tue, 24th Mar 2015 13:37    Post subject:
event handlers are a nightmare if you spam them everywhere
do was PA suggested and reuse a single bind like that and sort it out in the callback function

also, this
http://www.elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/
Back to top
PumpAction
[Schmadmin]



Posts: 26759

PostPosted: Tue, 24th Mar 2015 13:49    Post subject: Re: Dynamic selector
Interinactive wrote:
Is there any reason this shouldn't work?

Code:
      var question = 1;
      $("ul#question"+question+" li").on( "click", function(e) {
         dowhatever();
         question++;
      });


The selector doesn't seem to work after the first time, despite the fact that I can see the change in the console
I should also give you the reason why your solution won't work.

When your application runs, it sees this line $("ul#question"+question+" li").on( "click", function(e) {... and it will fill the question variable correctly with the value 1.

Now if you change the question variable itself, the event handler will still only exist for the question1 as you did not crate a new event handler after you increased the value of question.

You don't want to slow down the browser or use up unnecessary ram by creating too many event handlers anyway, so just use my solution Razz


=> NFOrce GIF plugin <= - Ryzen 3800X, 16GB DDR4-3200, Sapphire 5700XT Pulse
Back to top
Page 1 of 1 All times are GMT + 1 Hour
NFOHump.com Forum Index - Programmers Corner
Signature/Avatar nuking: none (can be changed in your profile)  


Display posts from previous:   

Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB 2.0.8 © 2001, 2002 phpBB Group