I have a script that displays one div at a time while hiding the previous shown div. When a button is clicked, the counter variable increases by one and the naming of the div id's are "step1", "step2", "step3", etc. Here is the script:
<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
开发者_如何学JAVA // 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>
This is where the variable is being incremented when clicked:
<div class="toggle_button">
<a href="#" onClick="counter = counter + 1" id="toggle_value"></a>
</div>
Here is my hidden 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>
The script works wonderfully and does what it needs, until id's with double digits and ending with a "0" (10, 20, 30, 40, etc...). For example: when the counter = 1, div id step1 and div id step10 are being shown on the page. When the counter = 10, only div id step10 is being shown. Div id step11 is shown at the appropriate time so I have narrowed it down to double digits ending in 0. I will never have more than 100 steps so only ending double digits or less are being used.
Are 0's at the end of a div id being ignored and being seen step1 and step10? I know you can't use a numeric value at the beginning of a id but it also states any number of [0-9] after the alphabetic character.
Thank you
Instead of using match(), just check for equality:
// filter to only the div in question
.filter( function() { return this.id == 'step' + counter; })
Example: http://jsfiddle.net/TAQZQ/
match() is intended for searching a string with a regular expression and returning the matches.
Don't use this.id.match
as it will try to match anywhere in the ID. Instead, try this.id =
as follows:
.filter( function() { return this.id == 'step' + counter; })
精彩评论