Evaluate a data-attibute on a div with jQuery and pass the value into a function

可紊 提交于 2019-12-11 06:28:22

问题


I have multiple slideshow blocks with preview images (for jQuery Cycle, each slideshow instance with a different delay in milliseconds) like this:

<div class="content">
    <div class="slideshow preview" data-delay="-2000">
        <img src="media/prevslide_3.jpg" alt="Img 1" />
        <img src="media/prevslide_4.jpg" alt="Img 2" />
        <img src="media/prevslide_5.jpg" alt="Img 3" />
    </div>
</div>

I want to use jQuery to pass these varying delay values (set via data-attribute)into the function that will run all occurences of Cycle.

$(document).ready(function() {

$('.slideshow.preview').cycle({
    fx: 'scrollHorz',
    random: 1,
    speed: 300,
    timeout: 6000,
    // here, for a single slideshow, delay is set like this "delay: -1234"
});
});

How does one evaluate the data-attribute on the div - data-delay="-2000" - and passes it into the Cycle function?

Many thanks in advance!


回答1:


jQuery has the .data() method which works with the html5 data attributes.

$(document).ready(function() {
    $('.slideshow.preview').cycle({
        fx: 'scrollHorz',
        random: 1,
        speed: 300,
        timeout: 6000,
        delay: $(".slideshow.preview").data("delay")
    });
});

EDIT

I missed the delay key, but this works. FIDDLE



来源:https://stackoverflow.com/questions/11335424/evaluate-a-data-attibute-on-a-div-with-jquery-and-pass-the-value-into-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!