3

希望我的措辞正确......

我正在尝试将元素 id 作为 jquery 函数中的选项传递:

        $('.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     });

在函数本身中,选项定义为o,所以我可以执行以下操作:

alert(o.fade);

它将显示一个显示“300”的警报。但是,如果我这样做:

alert(o.theid);

它说未定义。为什么?

4

2 回答 2

2

this不是你的对象。我猜你的.carousel每个班级都有一个 Id 并且你想将它分配给 theid 参数。但是,在您创建的对象中,上下文(this参数)与您的 jQuery 元素不匹配,它与您创建汽车的函数匹配。因此,您正在创建的 jQUery 对象包装了一个空的 HTML 元素并且没有 id。因此它被设置为未定义。

我认为这将完成您正在尝试做的事情:

$('.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正确设置上下文并应用createcarousel函数。

于 2012-12-07T23:49:59.623 回答
0
theid: $(this).attr('id')

在这种情况下,$(this) 是指轮播对象,它不是 html 对象。

查看 jquery 应用功能。您可以指定函数调用的上下文

http://api.jquery.com/Types/?rdfrom=http%3A%2F%2Fdocs.jquery.com%2Fmw%2Findex.php%3Ftitle%3DTypes%26redirect%3Dno#Context.2C_Call_and_Apply

滚动到“上下文、调用和应用”

希望这会有所帮助


考虑到您对另一个答案的评论:

那你就不需要传递id了!试试这个 :

$(".carousel").click(function(event){ 
    alert(event.target.attr("id")); 
}); 

event.target 代表被点击的html对象

这应该可以解决

于 2012-12-07T23:50:54.533 回答