1

在 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>
4

3 回答 3

2

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

 <select id="worktopColour" onchange="newTexture();">


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

使用imagevalue变量。

于 2012-10-01T10:43:36.713 回答
1

修改功能:jsfiddle

 document.worktopForm.worktopColour.onchange =newTexture;

function newTexture() {

        var textureName = '<img src="' + this.value + '.jpg">';
        document.getElementById("texture").innerHTML += textureName;        
}​
于 2012-10-01T10:44:15.183 回答
0

像这样的东西?

<!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>
于 2012-10-01T12:04:52.747 回答