有时似乎有效,有时却没有。使用它非常粗糙和可怕。
简化布局:
var index = 1
function next() {
if (index <= 4){
window.location.replace('#r' + index.toString());
index++;
}
}
function previous() {
if (index > 1){
index--;
window.location.replace('#r' + index.toString());
}
}
.what {
height: 500px;
}
<a href="#" onclick='next()' id="nxt">Next</a>
<a href="#" onclick='previous()' id="prev">Previous</a>
<body>
<table>
<tr class="what">
<td id="r1">r</td>
<td>o</td>
<td>w</td>
<td>1</td>
</tr>
<tr class="what">
<td id="r2">r</td>
<td>o</td>
<td>w</td>
<td>2</td>
</tr>
<tr class="what">
<td id="r3">r</td>
<td>o</td>
<td>w</td>
<td>3</td>
</tr>
<tr class="what">
<td id="r4">r</td>
<td>o</td>
<td>w</td>
<td>4</td>
</tr>
</table>
</body>
出于某种原因,它似乎只适用于id#r1和id#r4。有没有更好,更顺畅的方法呢?
答案 0 :(得分:1)
链接仍然在做他们通常做的事情。这意味着尝试将位置设置为#r1
与尝试将位置设置为#
之间存在干扰。
相反,请通过javascript设置事件处理程序,并使用preventDefault()
阻止链接执行默认操作。
我冒昧地纠正了其他一些小错误。
var index = 0
function next(event) {
if (index < 4){
index++;
window.location.replace('#r' + index.toString());
}
event.preventDefault();
}
function previous(event) {
if (index > 1){
index--;
window.location.replace('#r' + index.toString());
}
event.preventDefault();
}
document
.getElementById('nxt')
.addEventListener( 'click', next );
document
.getElementById('prev')
.addEventListener( 'click', previous );
&#13;
table {
width:100%;
}
.what {
height: 100px;
margin: 10px;
background-color: pink;
}
&#13;
<a href="#" id="nxt">Next</a>
<a href="#" id="prev">Previous</a>
<body>
<table>
<tr class="what">
<td id="r1">r</td>
<td>o</td>
<td>w</td>
<td>1</td>
</tr>
<tr class="what">
<td id="r2">r</td>
<td>o</td>
<td>w</td>
<td>2</td>
</tr>
<tr class="what">
<td id="r3">r</td>
<td>o</td>
<td>w</td>
<td>3</td>
</tr>
<tr class="what">
<td id="r4">r</td>
<td>o</td>
<td>w</td>
<td>4</td>
</tr>
</table>
</body>
&#13;
答案 1 :(得分:1)
var index = 1
function next() {
if (index < 4){
index++;
window.location.hash=('#r' + index.toString());
console.log('next',window.location.hash)
}
}
function previous() {
if (index > 1){
index--;
window.location.hash=('#r' + index.toString());
console.log('prev',window.location.hash)
}
}
.what {
height: 500px;
}
<a href="javascript:void(0)" onclick='next()' id="nxt">Next</a>
<a href="javascript:void(0)"onclick='previous()' id="prev">Previous</a>
<body>
<table>
<tr class="what">
<td id="r1">r</td>
<td>o</td>
<td>w</td>
<td>1</td>
</tr>
<tr class="what">
<td id="r2">r</td>
<td>o</td>
<td>w</td>
<td>2</td>
</tr>
<tr class="what">
<td id="r3">r</td>
<td>o</td>
<td>w</td>
<td>3</td>
</tr>
<tr class="what">
<td id="r4">r</td>
<td>o</td>
<td>w</td>
<td>4</td>
</tr>
</table>
</body>