【问题标题】:Reflect select state in javascript function在javascript函数中反映选择状态
【发布时间】:2012-10-01 10:41:08
【问题描述】:

在 javascript 中,如何使函数随时可以更改?我想这样做,以便当有人从下拉表单中选择不同的选项时,将出现该所选类型的图像。比如这样的:

        newTexture(document.worktopForm.worktopColour.value);

    function newTexture() {
            var textureName = '<img src="'document.worktopForm.worktopColour.value'.jpg>';
            document.getElementById("texture").innerHTML += textureName;        
    }


        <form name="worktopForm">

        <label>Choose colour of Worktop (Please select one)</label><br/>
        <select name="worktopColour">
            <option value="none" selected></option>
            <option value="starGalaxy">Star Galaxy (££)</option>
            <option value="tanBrown">Tan Brown (£££)</option>
            <option value="coolColour">Cool Colour (££££)</option>
            <option value="nutYellow">Nut Yellow (£££££)</option>
        </select>

        <div id="texture"></div></form>

【问题讨论】:

    标签: javascript-events forms javascript


    【解决方案1】:

    您可以在selectonchange 事件上调用任何函数

     <select id="worktopColour" onchange="newTexture();">
    
    
     function newTexture() {
            var textureName = document.getElementById("worktopColour");
            var  imagevalue=textureName.options[textureName.selectedIndex].value;        
     }
    

    使用imagevalue 变量。

    【讨论】:

    • 谢谢,这对我帮助很大。我现在已经这样做了,但是我在显示图像时遇到了问题。我已在函数中输入控制台日志“This Works”,该函数正在运行,但我对这些值所做的图像仍然不会显示。
    【解决方案2】:

    修改函数:jsfiddle

     document.worktopForm.worktopColour.onchange =newTexture;
    
    function newTexture() {
    
            var textureName = '<img src="' + this.value + '.jpg">';
            document.getElementById("texture").innerHTML += textureName;        
    }​
    

    【讨论】:

      【解决方案3】:

      这样的?

      <!DOCTYPE html>
      <meta charset=UTF-8><!-- validates as html5 -->
      <title>select from list</title>
      <script>
      function go () {
         var e = document.getElementById('worktopColour');
         document.getElementById('texture').innerHTML += 
         e.options[e.selectedIndex].value+'.jpg <br>';
      }
      </script>
      
      <form>
      <label>Choose colour of Worktop</label><br>
      <select id=worktopColour onChange=go()>
         <option value=none selected=selected>
         <option value=starGalaxy>Star Galaxy (££)
         <option value=tanBrown>Tan Brown (£££)
         <option value=coolColour>Cool Colour (££££)
         <option value=nutYellow>Nut Yellow (£££££)
      </select></form>
      <div id=texture></div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-03
        • 1970-01-01
        • 2023-04-04
        • 2020-08-10
        • 1970-01-01
        • 1970-01-01
        • 2020-01-09
        • 2020-03-11
        相关资源
        最近更新 更多