简体   繁体   中英

Increment, decrement href in JavaScript

I have an image gallery that I would slide by two buttons.

The values from the database:

<?php

$sql = "SELECT * FROM struttura ORDER BY id_img";
$result = $pdo->query($sql);

while ($row = $result->fetch())
{
    $id_img = $row['id_img'];
    $file = $row['file'];
    $text = $row['text'];
    ?> 
    <li><img src="images/<?php echo htmlspecialchars($file, ENT_QUOTES, 'UTF-8');?>" id="<?php echo htmlspecialchars($id_img, ENT_QUOTES, 'UTF-8');?>" /></li>
    <?php
}
?>

This is the div for navigation

<div class="navigation">
<a href="#" class="nav_prev js-shown">Prev</a>
<a href="#" class="nav_btn"></a>
<a href="#" class="nav_btn"></a>
<a href="#" class="nav_next js-shown">Next</a>
</div>

How can I increase or decrease the value of href in this way using JavaScript?

<a href="#1" class="nav_btn"></a>
<a href="#2" class="nav_btn"></a>
<a href="#3" class="nav_btn"></a>
...

Thank you in advance!

with pure javascript

var link = document.getElementsByClassName('nav_btn');
for(var i = 0; i< link.length; i++){

    link[i].href = '#'+(i+1);
    link[i].innerHTML = '#'+(i+1);

}

you can use jquery each loop

$( function(){

    $('.navigation').find('.nav_btn').each(function(i){
        var $this = $(this);
        $this.attr('href','#'+i); // this will return from #0 you can this with '#'+i+1
    });

} )

What I would do is get the total number of elements with the class as nav_btn using the

var x=$(".nav_btn").length;

You can then set a variable as y=0 .On pressing the next button, you could increase it, and update the href.

If you ever need to change an attribute, there is a setAttribute method.

When you hit the max count(==length), reset to zero. Similar flow for previous button.

Also, I would strongly suggest you check the next() function in Jquery.Check link for documentation: link

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