|
Page 1 of 1 |
|
Posted: 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 |
|
 |
|
Posted: 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);
});
|
|
Back to top |
|
 |
|
|
Back to top |
|
 |
|
Posted: 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 
|
|
Back to top |
|
 |
Page 1 of 1 |
All times are GMT + 1 Hour |
|
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
|
|
 |
|