Reputation: 37
I want to have next link on my page for viewing next episodes. I want to do it by increments. I have this but does not work.
<p><a id="asdf" href="sample-1">Next</a>
<script>
document.getElementById('asdf').addEventListener('click', function(e) {
var n = e.target.href.split('-')[1] * 1 + 1;
if (n > 4)
n = 1;
e.target.href = e.target.href.split('-')[0] + '-' + n + ".php";
}, false);
</script>
<div class="div3">
<ul>
<li><a href="sample-1.php">Anohana Ep1</a></li>
<li><a href="sample-2.php">Anohana Ep2</a></li>
<li><a href="sample-3.php">Anohana Ep3</a></li>
</ul>
</div>
Should I determine first the file name of current page?
Upvotes: 1
Views: 70
Reputation: 193261
Use parseInt
to convert to number:
document.getElementById('asdf').addEventListener('click', function (e) {
var n = parseInt(e.target.href.split('-')[1]) + 1;
if (n > 4) n = 1;
e.target.href = e.target.href.split('-')[0] + '-' + n + ".php";
}, false);
Explanation. The problem with your code is that after the first click href
turns into sample-1.php
. Which when split produces an array ['sample', '1.php']
. When you then try to convert 1.php
to number with multiplication operator *
it returns NaN
of course. So you should use parseInt
in this case which will extract numeric part properly.
Upvotes: 2