0
我正在寫一點練習,將事物從一個「select」移動到另一個「select」。很棒!我還沒有多選,但我會稍後再做。更重要的是,我想我會添加計數器,以便與「選項」相關聯的值可以相加。該功能似乎不起作用。當我將東西從一列移動到另一列時,用於求和值的標籤填充文本0 [對象對象]。我相信這是由於一個非常明顯的錯誤,但我缺乏用任何其他術語表達問題的詞彙。請教我? :-)JavaScript-DHTML:對象值訪問
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<style type="text/css">
#selectSource {
width: 320px;
}
#selectTarget {
width: 320px;
}
#wgtsum {
width: 22px;
}
#cubesum {
width: 22px;
}
</style>
<title>Loader</title>
<script>
var data;
var sumCube = 0;
var sumWgt = 0;
window.onload = function() {
//Add way to load JSON data from a text file or something
var load = document.getElementById('selectSource')
data = [
{ num: "1", cube: 6, wgt: 2, title: "num: 1 cube: 6 wgt: 2" },
{ num: "2", cube: 4, wgt: 4, title: "num: 2 cube: 4 wgt: 4" },
{ num: "3", cube: 2, wgt: 6, title: "num: 3 cube: 2 wgt: 6" }
];
for (i = 0; i < data.length; i++) {
load.options.add(new Option(data[i].title, data[i].num));
}
}
function sum() {
var sumTarget = document.getElementById('selectTarget');
for (i = 0; i < data.length; i++) {
for (o = 0; o < sumTarget.length; o++) {
if (sumTarget[o].value = data[i].value) {
sumCube = sumCube + data[i].cube;
sumWgt = sumWgt + data[i].wgt;
}
}
}
document.getElementById("cubesum").setAttribute("value", sumCube);
document.getElementById("wgtsum").setAttribute("value", sumWgt);
}
function move(from, to) {
selected = from.options.selectedIndex;
to.options.add(new Option(from.options[selected].text, from.options[selected].value));
from.options.remove(selected);
sum();
}
</script>
</head>
<body>
<form>
<select id="selectTarget" size="4">
</select>
<button type="button" onclick="move(this.form.selectSource, this.form.selectTarget)" style="width: 58px">To Target</button>
<button type="button" onclick="move(this.form.selectTarget, this.form.selectSource)" style="width: 58px">To Source</button>
<select id="selectSource" size="4">
</select>
<input value="0" type="text" id="cubesum" size="5"/>
<input value="0" type="text" id="wgtsum" size="5"/>
</form>
</body>
</html>
這可能是我所做的值的格式不會將它們存儲爲整數?我怎麼能解決這個問題? JavaScript中最好的數組/對象符號是什麼? – broguesquadron