【问题标题】:Query if else if else check true?查询 if else if else 检查是否为真?
【发布时间】:2015-04-29 19:31:02
【问题描述】:

您好,我想检查一个 div 是否有活动的类。 第一项工作,之后它停止。有人可以告诉我如何解决这个问题吗? (它是一个滑块,所以它不能在点击时工作。)它会自动滑动。 http://i61.tinypic.com/28h2zb6.jpg

    <script>
$(document).ready(function () {
  if ($('#211').hasClass('item active')){
            $('.vandaag').css("background-color", "blue");
            console.log("werkt1!");}
   else if ($('#218').hasClass('item active')){
            $('.vandaag').css("background-color", "#005993");
            console.log("werkt2!");}

    else if ($('#219').hasClass('active')){
            $('.vandaag').css("background-color", "#005993");
            console.log("werkt3!");}
});

</script>

数字是图像滑块的 id。并且 .item .active 是幻灯片处于活动状态时。 问候

【问题讨论】:

    标签: javascript jquery if-statement


    【解决方案1】:

    不要使用else if,因为它会在第一个块工作后停止。

    改为使用if() { } 块。

     $(document).ready(function() {
            if ($('#211').hasClass('item active')) {
                $('.vandaag').css("background-color", "blue");
                console.log("Works!");
            } 
            if ($('#218').hasClass('item active')) {
                $('.vandaag').css("background-color", "#005993");
                console.log("works2!");
            }
            if ($('#219').hasClass('active')) {
                $('.vandaag').css("background-color", "#005993");
                console.log("works3!");
            }
        });
    

    【讨论】:

    • 对我不起作用..我必须让 (document).ready 出来吗?我只得到第一个 console.log “Works!”返回
    • 您确定#218 和#219 处于活动状态吗?它绝对应该可以工作,并且问题与 Javascript 无关。 Document.ready 仅表示页面加载完成后执行脚本。
    • 你告诉我是的,但他们不活跃...class="item" 而不是class="item active"
    • 它是一个滑块,第一个 #211 处于活动状态。 8 秒后幻灯片 #218 处于活动状态,然后 #219 重新开始。
    • 这就解释了为什么。当您使用$(document).ready 时,代码在页面加载时执行,并且只执行一次。例如,您需要再次执行代码以检查 8 秒。我建议使用 events 来代替。
    【解决方案2】:

    如果要执行多个条件,则不需要 else 条件:

     $(document).ready(function () {
       if ($('#211').hasClass('item active')){
          $('.vandaag').css("background-color", "blue");
          console.log("Works!");}
       if ($('#218').hasClass('item active')){
          $('.vandaag').css("background-color", "#005993");
          console.log("works2!");}
       if ($('#219').hasClass('active')){
          $('.vandaag').css("background-color", "#005993");
          console.log("works3!");}
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多