简体   繁体   English

为什么我的 jquery 代码不起作用?

[英]why my jquery code is not working?

<script>
        var i=0;
        $(document).ready(function(){
           $("#tolevel_" + (i+1) ).click(function(){
              $("#level_" + i).hide(500,'swing', function(){
                  $("#level_" +(i+1)).show(500, 'swing', function(){
                      i=i+1;
                  });

              });
           });
            $("#backtolevel_" + (i-1) ).click(function(){
                $("#level_" + i).hide(500,'swing', function(){
                    $("#level_" +(i-1)).show(500, 'swing', function(){
                        i=i-1;
                    });
                });
            });
        });
    </script>

Ok here is my jquery.好的,这是我的 jquery。 The level ids are divs and tolevel and backtolevel are two buttons in each.级别 id 是 divs,而 tolevel 和 backtolevel 是每个中的两个按钮。 for example if the div id is "level_1" the ids of the buttons in that div are "backtolevel_0" and "tolevel_2".例如,如果 div id 为“level_1”,则该 div 中按钮的 id 为“backtolevel_0”和“tolevel_2”。 Ok it only works the first time.好吧,它只在第一次工作。 it doesn't matter on what level I am.我处于什么水平并不重要。 I have tested it on different levels but it only works once.我已经在不同级别上对其进行了测试,但它只能工作一次。 don't know why!不知道为什么! can you guys help me?你们能帮帮我吗? I think somewhat the incrementing or decrementing are not working.我认为有些递增或递减不起作用。

Try with following code:尝试使用以下代码:

<script>

        $(document).ready(function(){
           $("[id^=tolevel_]").click(function(){
                var currentID = $(this).attr("id");
                var number = currentID.replace("tolevel_","");//get the number in string format
                number = parseInt(number);
                var i = number -1;
                $("#level_" + i).hide(500,'swing', function(){
                  $("#level_" +(i+1)).show(500, 'swing', function(){

                  });
                });
           });

            $("[id^=backtolevel_]").click(function(){
                var currentID = $(this).attr("id");
                var number = currentID.replace("backtolevel_","");//get the number in string format
                number = parseInt(number);
                var i = number + 1;
                $("#level_" + i).hide(500,'swing', function(){
                    $("#level_" +(i-1)).show(500, 'swing', function(){

                    });
                });
            });
        });
    </script>

It user `jquery's Attribute Starts With Selector.它用户`jquery 的属性以选择器开始。 See more about it at https://api.jquery.com/attribute-starts-with-selector/ .https://api.jquery.com/attribute-starts-with-selector/查看更多相关信息。 Really no need to write code for each and every element.真的不需要为每个元素编写代码。 This should work.这应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM