I have a piece of code that on hover of another element insert's this code below.
<div class="star" id="1">
<div class="star" id="2">
<div class="star" id="3">
<div class="star" id="4">
<div class="star" id="5">
</div>
</div>
</div>
</div>
</div>
All I want to do is retrieve the ID of each DIV through javascript:
$(document).ready(function() {
$('.star').on(function(e){
e.stopPropagation();
var rating = $(this).attr('id');
alert(rating);
});
});
I've tried many ways of achieving this, this is the latest I've tried but I'm still having no luck! I'll be grateful of any help
-
Freaking easier to just do it next to where the DIVs are inserted. Any reasons why not to do it? Probably I misunderstood you question thoughAlexander– Alexander2012年12月22日 19:51:05 +00:00Commented Dec 22, 2012 at 19:51
-
Agreed, you need to either alter that code, or if that's not possible, then attach another event handler to the hover event of it, and then run the $('.star')... code (perhaps after a slight delay to ensure your code runs after the insert of the divs).MadSkunk– MadSkunk2012年12月22日 19:57:24 +00:00Commented Dec 22, 2012 at 19:57
3 Answers 3
Trigger an event when said divs are added.
var counter = 0;
$(someelement).on("mouseenter",function(){
counter++;
$('<div class="star" id="' + counter + '" />').appendTo(".star:last").trigger("staradded");
})
$(document).on("staradded",".star",function(e) {
alert(this.id);
});
Or better yet, skip the event.
var counter = 0;
$(someelement).on("mouseenter",function(){
counter++;
$('<div class="star" id="' + counter + '" />').appendTo(".star:last");
alert(counter);
})
1 Comment
I would use "livequery" plugin - https://github.com/brandonaaron/livequery
If I understood correctly, you need something like old function "live", since you would like to watch all new ".star" elements.
In this case you will just use following code:
$('.star').livequery('click',function(e){});
Simple example you can find there - http://jsfiddle.net/WEr5J/11/
Comments
You have wrong syntax of on as you are not telling what event you want to bind. After binding your required event e.g. click you can use map function to get all the comma separated ids of elements having class star.
$(document).on('click', '.star', function(e) {
e.stopPropagation();
ids = $('.star').map(function() {
return this.id;
}).get().join();
alert(ids);
});
You need to use each to iterate through all elements.
$('.star').each(function(){
var rating = $(this).attr('id');
alert(rating);
});