【问题标题】:Making a quote roller with buttons and timer使用按钮和计时器制作报价滚筒
【发布时间】:2014-03-18 06:41:43
【问题描述】:

我们正在尝试制作带有按钮和计时器的报价滚轮。我们已经走了很远,但此时按钮无法正常工作,这是一个 jsfiddle:http://jsfiddle.net/BaXXg/1/

这里是代码

var quotes = [
    "Quote1<br><br>  -  Repomeri",
    "Quote2 <br><br> - Emmi",
    "Quote3<br><br> - Taateli",
    "Quote4<br><br> - Joonas",
    "Quote5<br><br> - Eskelinen",
];

var i = 0;
var timer = null;

setInterval(function() {
    $("#slideContainer").html(quotes[i]);
    if (i == quotes.length) {
        i = 0;
    } else {
        i++;
    }
}, 4 * 1000);


var b1 = document.getElementById('b1'),
    b2 = document.getElementById('b2'),
    b3 = document.getElementById('b3'),
    b4 = document.getElementById('b4'),
    b5 = document.getElementById('b5');


b1.onclick = function() {
    $("#slideContainer").html(quotes[i]);
    i = 0;
};

b2.onclick = function() {
    $("#slideContainer").html(quotes[i]);
    i = 1;
};

b3.onclick = function() {
    $("#slideContainer").html(quotes[i]);
    i = 2;
};

b4.onclick = function() {
    $("#slideContainer").html(quotes[i]);
    i = 3;
};

b5.onclick = function() {
    $("#slideContainer").html(quotes[i]);
    i = 4;
};

【问题讨论】:

  • 您可以简化代码,因为您已经在使用 jQuery。看我更新的演示jsfiddle.net/Godinall/BaXXg/8你最后30行代码实际上可以用jQuery写成3行。

标签: javascript jquery html slider quotes


【解决方案1】:

我认为您必须先将作业分配给i,然后再调用html(quotes[i])。例如:

b1.onclick = function() {
    i = 0;
    $("#slideContainer").html(quotes[i]);
};

【讨论】:

    【解决方案2】:

    你必须在$("#slideContainer").html(quotes[i]);之前设置变量i

    您也可以使用class 并减少您的代码:

    HTML:

    <input type="button" class="btn" value="" id="b1">
    <input type="button" class="btn" value="" id="b2">
    <input type="button" class="btn" value="" id="b3">
    <input type="button" class="btn" value="" id="b4">
    <input type="button" class="btn" value="" id="b5">
    

    JS:

    $('.btn').click(function () {
        i = $(this).attr('id').substr(1);
        i--;
        $("#slideContainer").html(quotes[i]);   
    });
    

    FIDDLE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-14
      • 1970-01-01
      相关资源
      最近更新 更多