<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. The level ids are divs and tolevel and backtolevel are two buttons in each. for example if the div id is "level_1" the ids of the buttons in that div are "backtolevel_0" and "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. See more about it at https://api.jquery.com/attribute-starts-with-selector/ . Really no need to write code for each and every element. This should work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.