简体   繁体   中英

How can I use javascript and jquery to change a text value when next and previous buttons are pressed?

I have the following HTML with a value of "1-99" visible:

<ul class="controls-buttons question-controls">

   <li>
      <a href="#" title="Previous" id="orderPrevious><img src="/Images/control-double-180.png"></a>
   </li>
   <li>
      <a id="orderRange">1 - 99</a>
   </li>

   <li>
      <a href="#" title="Next" id="orderNext"><img src="/Images/control-double.png"></a>
   </li>             
</ul>

Is there a way that I can have the orderRange change so it changes like this when the previous and next links are clicked? Ideally I would like some way that doesn't mean I have to hardcode a lot of if and else statements.

                1-99      > 100-199
1-99      < 100-199 > 200-299
100-199 < 200-299 > 300-399
200-299 < 300-399
etc ..

Once changed I would like to store the value using local storage like below:

   var store = window.localStorage;
   store.setItem('Range', xxx)

I hope someone can help me.

function changeRange(delta){
   var orderRange=document.getElementById('orderRange'),
   range=orderRange.innerHTML.split(' - ')
   range=[parseInt(range[0])+delta,parseInt(range[1])+delta]
   if(range[0]<0) return
   orderRange.innerHTML=range.join(' - ')
   var store = window.localStorage;
   store.setItem('Range', orderRange.innerHTML)
}
document.getElementById('orderNext').onclick=function(){changeRange(100);}
document.getElementById('orderPrevious').onclick=function(){changeRange(-100);}

Here's a solution :

function change(d) {
    var $field = $('#orderRange');
    var nums = $field.text().split('-').map(function(a){return parseInt(a,10)+d*100});
    if (nums[0]<0) return;
    else if (nums[0]==101) nums[0]=100;
    else if (nums[0]==0) nums[0]=1;
    $field.html(nums.join(" - "));
}

$('#orderPrevious').click(function(){change(-1)});
$('#orderNext').click(function(){change(+1)});

Demonstration

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.

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