为什么不能用我的变量调用这个函数?

时间:2014-06-19 11:26:45

标签: jquery

我试图用两个变量调用函数:

$('#sub-nav li a').on('click', function(event) {
    event.preventDefault(event);

    // Which slider to use
    var $sliderNo = $(this).attr('data-slider');
    var $slider = "#flexslider" + $sliderNo;

    // Which slide to show
    var $slide = $(this).attr('data-slide');

    // Lets say i click on the link for slider 1, and the link for slide 1:
    alert($slide); // This will alert correct data-slide number
    alert($slider); // This will alert: '#flexslider1'

    $("#flexslider1").flexslider(1); //This will run!
    $($slider).flexslider($slide); // This won't run! - Why?
});

为什么我不能用$ variables调用$($slider).flexslider($slide);

1 个答案:

答案 0 :(得分:2)

试试这个

$('#sub-nav li a').on('click', function(event) {
    event.preventDefault();

    // Which slider to use
    var $sliderNo = $(this).data('slider');
    var $slider = "#flexslider" + $sliderNo;

    // Which slide to show
    var $slide = $(this).data('slide');

    // Lets say i click on the link for slider 1, and the link for slide 1:
    alert($slide); // This will alert correct data-slide number
    alert($slider); // This will alert: '#flexslider1'

    $("#flexslider1").flexslider(1); //This will run!
    $($slider).flexslider($slide); // This won't run! - Why?
});