我的作业要求我使用HTML和JavaScript对网站进行编码。该网站只是一个关于太阳系中行星的非常基本的网站(我是一名刚开始使用HTML的计算机科学专业的学生)。
该网站包含两个按钮,您将在下面的代码中看到,它将屏幕上的文字更改为太阳系中的下一个星球,但有时单击按钮时不会发生这种情况,而是文本改变错误的星球或简单地说“未定义”,直到网站继续正常工作时再点击几次按钮。
这是我的代码:
<html>
<body bgcolor="cyan">
<h1>The Solar System</h1>
<script>
var planets= ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"];
var endofplanets=planets.length;
var i =0;
function nextplanet(){
if (i<endofplanets){
document.getElementById('p1').innerHTML=planets[i];
i++;
}
}
</script>
<script>
function previousplanet(){
if (i>-1){
document.getElementById('p1').innerHTML=planets[i];
i--;
}
}
</script>
<p id="p1">---</p>
<button type="button" onclick=nextplanet()>Next Planet</button>
<button type="button" onclick=previousplanet()>Previous Planet</button>
</body>
</html>
非常感谢任何帮助
答案 0 :(得分:0)
检查一下: - 你需要在下一个按钮中添加else条件并将i值重置为0,这是小提琴https://jsfiddle.net/3bsyypL9/2/
\S
答案 1 :(得分:0)
DHRUV GUPTA的答案包含错误,当i等于7时,如果你执行nextplanet(),则i增加1。因此,如果你触发函数previousplanet(),我等于8,你得到一个未定义的结果。
避免此错误的最简单方法是不要每次都增加i。 检查一下: http://codepen.io/anon/pen/EZbBVX
NO LOOP VERSION
i = -1; //To be sure that the first planet will be Mercury
function nextplanet(){
if (i<endofplanets){
i = Math.min(i+1,endofplanets-1); //Take the minimum between i+1 and last indice of your array (7), so i will ever be lower of equal to the max indice of your array
document.getElementById('p1').innerHTML=planets[i];
}
}
function previousplanet(){
if (i>-1){
i = Math.max(i-1,0); //The same, i will be ever greater or equal to 0, which is the lower indice of your array ;)
document.getElementById('p1').innerHTML=planets[i];
}
}
循环版本
i = 0;
function nextplanet(){
document.getElementById('p1').innerHTML=planets[i];
i = (i+1) % endofplanets; //With a modulo, your indice is always between 0 and endofplanets-1, google modulo if you don't know this operator ;)
}
function previousplanet(){
document.getElementById('p1').innerHTML=planets[i];
i = (i-1) % endofplanets;
}
答案 2 :(得分:0)
试试这个简单的解决方案
var formComponent = React.createClass({
verifyFields: function (e) {
e.preventDefault();
if (this.state.primaryGuestName && this.state.primaryGuestMobile) {
// how can i continue with form submission here(not using xhr)
} else {
showErrors();
}
},
render: function () {
<form action={this.props.action} ref="booking_form" acceptCharset="UTF-8" method="post">
{form contents}
<a href="" name="submit_details" onClick={this.verifyFields}
className="btn-flat btn-large rd-button">Confirm Details</a>
</form>
}
}