我今天开始使用JavaScript进行编码,目前正在制作一个将100
添加到shark[0]
数组中的shark
的按钮。我正在使用数组来存储我拥有的数据。
我正在运行的问题是先保存更改后的数组,然后再以正确的数量更改数组。试图用谷歌搜索,但找不到答案。感谢您的帮助。
shark = [1200, 993, 0, 0]
shark[3] = shark[0] * (shark[1] - shark[2])
shark[0] = sharkAdd(shark[0], 1++, 100)
function sharkAdd(value, x, hundra) {
var value = parseInt(document.getElementById('sharkAmount').innerHTML = shark[0], 10);
value + x++ * 100;
}
shark.toString();
document.getElementById("sharkAmount").innerHTML = shark[0];
document.getElementById("sharkPrice").innerHTML = shark[1];
document.getElementById("sharkCost").innerHTML = shark[2];
document.getElementById("sharkProfit").innerHTML = shark[3];
HTML(这不是完整的HTML):
<button onclick="sharkAdd()" class="button button1" >Add 100 Sharks</button>
<td id="sharkAmount">1100</td>
答案 0 :(得分:2)
在执行此操作时,您似乎有些困惑,其中包含一些不可编译的代码,多余的内容以及变量的奇数分配,在这里确实无法解释和解释。
但是,这实际上是一项非常简单的工作。我已对代码进行了详细注释,以帮助您了解每一行的作用。
为简单起见,我从您的原始代码中省略了与问题不直接相关的部分。
//this section outside the function will run immediately when your page is loaded into the browser.
//initialise the data array (as a global variable)
var shark = [1200];
//get a reference to the "sharkAmount" HTML element (as a global variable)
var sharkAmountDisplay = document.getElementById('sharkAmount');
//initialise the display with the current value from the array
sharkAmountDisplay.innerHTML = shark[0];
//code inside this function will run only when it's called (e.g. from your "onclick" event in the HTML)
function sharkAdd(value) {
//"value" will be the "100" passed in by "sharkAdd(100)" in the HTML
//now, add the value to the existing value and store it in the array
shark[0] = shark[0] + value;
//update the display with the new value from the array
sharkAmountDisplay.innerHTML = shark[0];
}
<button onclick="sharkAdd(100)" class="button button1">Add 100 Sharks</button>
<br/><br/>
No. of sharks: <div id="sharkAmount"></div>
答案 1 :(得分:0)
这就是您所需要的。要将数据保存在客户端中,请使用window.localStorage。我将把这部分留给您实施。
var shark = [ 1200, 993, 0, 993]
function addSharks()
{
var sharkstoadd = 100;
shark[0] += 100;
shark[3] = shark[0] * (shark[1] - shark[2])
document.getElementById("sharkAmount").innerHTML = shark[0];
document.getElementById("sharkPrice").innerHTML = shark[1];
document.getElementById("sharkCost").innerHTML = shark[2];
document.getElementById("sharkProfit").innerHTML = shark[3];
}
<table class="table">
<thead>
<tr>
<th>Resource</th>
<th>Amount</th>
<th>Price ea</th>
<th>Cost ea</th>
<th>Profit</th>
</tr>
</thead>
<tbody>
<tr>
<td>Shark</td>
<td id="sharkAmount">1200</td>
<td id="sharkPrice">993</td>
<td id="sharkCost">0</td>
<td id="sharkProfit">0</td>
</tr>
</tbody>
</table>
<button onclick="addSharks()">Add 100 Sharks</button>