开发者

jQuery .live function problem

I have an element that gets an attribute added to it by jquery when the page loads. The attribute is called jcarouselindex. I need to get the value of this attribute when the document loads.

Ive got the selector and if it wasn't added dynamically could just do:

id = jQuery('#gallery-caro开发者_如何学Cusel li.selected').attr("jcarouselindex");

But since its been added dynamically the value of id is undefined. I think I need to use .live() does anyone know how I would get the value of this attribute please?


Your code above should work. .live() is used for a different purpose. I think you may be trying to access the attr before it is being dynamically added. Try calling this function using a setTimeout, which will ensure all the existing code gets executed.

setTimeout(function(){
    id = jQuery('#gallery-carousel li.selected').attr("jcarouselindex");
}, 0);

I'm assuming your code is already within a $(function(){}); block.


Live should be used to bind event handlers to elements which do not exists on the page at the time of binding.

I think you need to look at the execution timings that you have on the page. Your selector includes the class 'selected' on the li so I assume an event must trigger the addition of the selected class. does this event occur after the jcarouselindex attribute values have been added? if so then you should capture this value when the selection event occurs.

Unfortunately you have not given us much detail to go on so more info could help us to help you more.


live is not for that, but for event handlers. You have to run that code after the attribute has been set, so, try with:

$.ready(function(){
  id = jQuery('#gallery-carousel li.selected').attr("jcarouselindex");
});


Are using the jcarousel plugin?

If so there is a callback you can use on the initialisation of the carousel:

$('#gallery-carousel').jcarousel({
    initCallback: function () {
        var id = $('#gallery-carousel li.selected').attr("jcarouselindex");
        // do something with id
    }
});

This way you can be sure that the carousel has initialised before executing your code.

see: http://sorgalla.com/projects/jcarousel/ for further details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜