<!DOCTYPE html>
<html>
<body>
<select id='selectid' onchange="selectchange()">
</select>
<script>
for (let i=0;i<10;i )
{
var select = document.getElementById("selectid");
var option = document.createElement("option");
option.text = "text=" i;
option.value = i;
select.add(option);
}
function selectchange()
{
alert(document.getElementById("selectid").value);
}
</script>
</body>
</html>
描述
- 在這里,我一直在使用 javascript 為我的選擇標簽添加選項
我需要
- 我需要使用我現有的 javascript 代碼存盤多個資料,如 value=1 選項需要為選項標簽添加另一個值,如 value2=a,而 value=2 為 value2=b
示例語法
var select = document.getElementById("selectid");
var option = document.createElement("option");
option.text = "text=" i;
option.value = i;
option.value2 = a;
select.add(option);
我需要使用上述語法為我的選項添加兩個值。
uj5u.com熱心網友回復:
您可以嘗試使用setAttribute和getAttribute。
<!DOCTYPE html>
<html>
<body>
<select id='selectid' onchange="selectchange()">
</select>
<script>
for (let i=0;i<10;i ) {
var select = document.getElementById("selectid");
var option = document.createElement("option");
option.text = "text=" i;
option.value = i;
option.setAttribute("data", Math.random());
option.setAttribute("data1", `data1_${Math.random()}`);
select.add(option);
}
function selectchange() {
const select = document.getElementById("selectid");
const data = select.options[select.selectedIndex].getAttribute("data");
const data1 = select.options[select.selectedIndex].getAttribute("data1");
console.log(`value is: ${select.value} and data is: ${ data } data1 is: ${data1}`);
}
</script>
</body>
</html>
希望這就是你要找的!!
uj5u.com熱心網友回復:
第一個解決方案是使用資料屬性:
<!DOCTYPE html>
<html>
<body>
<select id='selectid' onchange="selectchange()">
</select>
<script>
for (let i = 0; i < 10; i ) {
var select = document.getElementById("selectid");
var option = document.createElement("option");
option.text = "text=" i;
option.value = i;
option.dataset['var-1'] = i;
option.dataset['var-2'] = 'value2';
option.dataset['var-3'] = 'value3'; // and etc.
select.add(option);
}
function selectchange() {
const selectedOption = document.getElementById("selectid").selectedOptions[0]
console.log(selectedOption.dataset);
}
</script>
</body>
</html>
第二種解決方案是使用外部變數來存盤額外的資料:
<!DOCTYPE html>
<html>
<body>
<select id='selectid' onchange="selectchange()">
</select>
<script>
const dataStore = {};
for (let i = 0; i < 10; i ) {
var select = document.getElementById("selectid");
var option = document.createElement("option");
option.text = "text=" i;
option.value = i;
select.add(option);
dataStore[i] = {
var1: i,
var2: 'var2',
var3: 'var3'
};
}
function selectchange() {
const index = document.getElementById("selectid").value
const value = dataStore[index]
console.log(value);
}
</script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/384952.html
標籤:javascript html
上一篇:型別錯誤[COMMAND_INTERACTION_OPTION_EMPTY]:所需選項“訊息”的型別:_MESSAGE;期望一個非空值。(Discord.js)
下一篇:javascript函式輸出問題
