簡體   English   中英

根據選擇選項更改表格單元格內容?

[英]Change table cell content based on select option?

這是選擇塊:

<form>
            <select id="select">
                <option disabled selected value="choose">
                    CHOOSE
                </option>
                <option value="i2g" id="i2g">
                    iPhone 2g
                </option>
                <option value="i3g" id="i3g">
                    iPhone 3g
                </option>
            </select>
            <button onclick="func1()" type="button">
                GO
            </button>
</form>

表格內容如下:

<table id="iphone1g" border="1">
            <tr>
                <td id="itable1">
                    1
                </td>
                <td id="itable2">
                    2
                </td>
            </tr>
        </table>

這是JavaScript:

<script>
            var x = document.getElementById("i2g")
            var y = document.getElementById("i3g")
            var m = document.getElementById("itable1")
            var n = document.getElementById("itable2")
            function func1(){
                if (x.selected = "true"){
                    m.innerHTML = "hello"
                } 
                if (y.selected = "true"){
                    m.innerHTML = "adele"
                }
            }
        </script>

沒用 我只能選擇整個選擇中的一個,也只能是最后一個。

單一等於用於分配而不是比較,您應該使用==或===來檢查是否選擇了這些值。

您還嘗試檢查字符串值true,而不是布爾值true(.selected返回true或false而不是“ true”或“ false”)

有了這兩個更改,它應該可以工作。

   var x = document.getElementById("i2g")
    var y = document.getElementById("i3g")
    var m = document.getElementById("itable1")
    var n = document.getElementById("itable2")
    function func1(){
        if (x.selected === true){
            m.innerHTML = "hello"
        } 
        if (y.selected === true){
            m.innerHTML = "adele"
        }
    }

首先,要比較Java腳本中的兩個對象,應使用== not =

此外,您應該按照本ananser中的指示從SELECT中檢索所選值。

好吧,讓我們分解一下。 首先,您缺少許多分號; 其次,您需要使用==在if語句內部進行比較,而不僅僅是= 第三,通常通過檢查所述選擇的值而不是每個單獨的選項來檢查選擇的值更容易。

這是一些工作代碼和一個工作演示

var m = document.getElementById("itable1");
var n = document.getElementById("itable2");

var select = document.getElementById("select");

function func1() {
  if (select.value == "i2g"){
    m.innerHTML = "hello";
  } 
  if (select.value == "i3g"){
    m.innerHTML = "adele";
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM