简体   繁体   中英

How to make next and prev buttons to navigate through a list and trigger their functions?

I have a slight problem which I cannot figure out how to do. I have a list. Clicking each list item changes background image and a text in a div. But I would also like to have a next/prev buttons for easy navigation. These next and prev buttons would change the background and text box accordingly. How would one do this?

This changes the background image:

<script type="text/javascript">
var backImage = [ 
'img/img.jpg',
'img/img2.jpg',
'img/img3.jpg',

];

function changeBGImage(evt, id){
var el = evt.target || evt.srcElement;
var ul = el.parentNode;
var lis = ul.getElementsByTagName('li');

for (var i=0, iLen=lis.length; i<iLen; i++) {
  if (lis[i] == el) {
        document.body.background = backImage[i];
        }
    }
}

</script>

and this changes the text in the ( <div id="fred"></div> ) box

<script type="text/javascript">

var MessAry = [
'text1',
'text2',
'text3',
 ];

function CngMess(evt, id) {
var el = evt.target || evt.srcElement;
var ul = el.parentNode;
var lis = ul.getElementsByTagName('li');

for (var i=0, iLen=lis.length; i<iLen; i++) {
  if (lis[i] == el) {
    document.getElementById(id).innerHTML = MessAry[i];
      }
    }
  }
</script>

then I have this in html. Clicking these list items changes the text and the background.

<ul onclick="CngMess(event, 'fred'); changeBGImage(event);">
    <li>listitem1</li>
    <li>listitem2</li><br>
    <li>listitem3</li><br>
</ul>

I have a live site here: http://heikkilotvonen.fi/

Would there be an easy way to implement a prev next buttons for this setting? Could anybody help?

Thanks!

In general, I would handle such a situation by keeping a "pointer" to the active element. For instance, you could store the DOM element corresponding to the active list item in a javascript variable. Then, when back and forward are clicked, you can navigate to the adjacent siblings of your list item.

Alternatively, you could simply store an integer id. Suppose your html looked like:

<li id="listItem_0" myCustomAttr="0">Stuff 1</li>
<li id="listItem_1" myCustomAttr="1">Stuff 2</li>
.....

Then you could store the value of your custom attribute, and then concatenate (n-1) or (n+1) to 'listItem_' and do a document.getElementById() to find the element you're going to next and take the same action as you would had it been clicked.

In summary, there are lots of ways to do this, but they will probably center around keeping track of the current item directly or indirectly in some sort of javascript variable.

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