隐藏的DIV和id命名结构

时间:2010-09-15 13:04:42

标签: javascript jquery html

我有一个脚本,一次显示一个div,同时隐藏前面显示的div。单击一个按钮时,计数器变量增加1,div id的命名为“step1”,“step2”,“step3”等。这是脚本:

<script language="javascript" type="text/javascript">
        var counter = 0;
        $('html').addClass('js'); // prevent hiding divs on DOM ready from 'flashing'
        $(function() {
                $('#toggle_value').click(function() {
                $('div','#hiddendiv')
                        // to stop current animations - clicking really fast could originally
                        // cause more than one div to show
                        .stop()
                        // hide all divs in the container
                        .hide()
                        // filter to only the div in questio
                        .filter( function() { return this.id.match('step' + counter); })
                        // show the div
                        .show()
                        // prevent default anchor click event
                        return false;
                });
        });
</script>

这是单击时变量递增的位置:

<div class="toggle_button">
        <a href="#" onClick="counter = counter + 1" id="toggle_value"></a>
</div>

这是我隐藏的div:

<div id='hiddendiv'>
        <div id="step1" class="display">
                <p>step 1 text</p>
        </div>
        <div id ="step2" class="display">
                <p>step 2 text</p>
        </div>
        <div id="step3" class="display">
                <p>step 3 text</p>
        </div>
        <div id ="step4" class="display">
                <p>step 4 text</p>
        </div>     
        <div id="step5" class="display">
                <p>step 5 text</p>
        </div>
        <div id ="step6" class="display">
                <p>step 6 text</p>
        </div>     
        <div id="step7" class="display">
                <p>step 7 text</p>
        </div>
        <div id ="step8" class="display">
                <p>step 8 text</p>
        </div>     
        <div id="step9" class="display">
                <p>step 9 text</p>
        </div>
        <div id ="step10" class="display">
                <p>step 10 text</p>
        </div>     
        <div id="step11" class="display">
                <p>step 11 text</p>
        </div>
</div>

该脚本运行得非常好并且能够满足需要,直到id为双位数并以“0”结尾(10,20,30,40等等)。例如:当counter = 1时,div id step1和div id step10将显示在页面上。当计数器= 10时,仅显示div id step10。 Div id step11在适当的时间显示,所以我把它缩小到以0结尾的两位数。我将永远不会超过100步,所以只使用了两位或更少的数字。

div id结尾的0是否被忽略并被看作step1和step10?我知道你不能在id的开头使用数字值,但它也会在字母字符后面加上任意数量的[0-9]。

谢谢

2 个答案:

答案 0 :(得分:3)

不要使用 match(),只需检查是否相等:

// filter to only the div in question
.filter( function() { return this.id == 'step' + counter; })

示例:http://jsfiddle.net/TAQZQ/

match()用于搜索带有正则表达式的字符串并返回匹配项。

答案 1 :(得分:1)

请勿使用this.id.match,因为它会尝试匹配ID中的任何位置。相反,请尝试this.id =,如下所示:

.filter( function() { return this.id == 'step' + counter; })
相关问题