Reputation: 10649
Hopefully I am wording this correctly...
I am trying to pass an element id as an option in a jquery function:
$('.carousel').createcarousel({
theid: $(this).attr('id'), // this is the part I am trying to get working
delay: 150,
fade:300,
slide: 700,
effect:'slide',
orientation:'horizontal',
loop: false,
autoplay: false });
Within the function itself, the options are defined as o
, so I can do something like:
alert(o.fade);
And it will display an alert showing "300". However, if I do:
alert(o.theid);
It says undefined. Why?
Upvotes: 3
Views: 3434
Reputation: 14863
this
isn't your object in your contect. I guess your .carousel
classes each have an I'd and you want to assign it to the theid argument. However, in the object you are creating the context (this
argument) doesn't match to your jQuery element, it matches to your function, where you create the caruses. So the jQUery object you are creating, wrappes an empty HTML element and has no id. Therefor it is set as undefined.
I think this will acomplish what you are trying to do:
$('.carousel').each(function() {
$(this).createcarousel({
//theid: $(this).attr('id'),
theid: this.id, //thanks jtheman
delay: 150,
fade:300,
slide: 700,
effect:'slide',
orientation:'horizontal',
loop: false,
autoplay: false });
});
This will iterate over all your carousel classes, set the this
context correctly and apply the createcarousel
function.
Upvotes: 2
Reputation: 2677
theid: $(this).attr('id')
In this context, $(this) refers to the carousel object which is not an html object.
Check out the jquery apply function. You can specify the context of a function call
scroll to "Context, Call and Apply"
Hope this helps out
Considering the comment you made on the other answer :
You don't need to pass the id then! try this :
$(".carousel").click(function(event){
alert(event.target.attr("id"));
});
event.target represents the html object which was clicked
This should work out
Upvotes: 0