根据html选择值调用不同的javascript函数 [英] call different javascript functions based on html select values

查看:83
本文介绍了根据html选择值调用不同的javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < select id =mySelectname =几何图形> 
< option> Circle< / option>
< option> Triangle< / option>
< option> Square< / option>
< option> Rectangle< / option>
< option> Polygon< / option>
< / select>
< button id =imagedrawonclick =draw()>绘制图像< / button>

我有不同的功能根据用户选择绘制画布图像

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ p>

我的查询是在执行 onclick 事件时,如何根据用户输入设置要动态调用的函数。
例如:当用户选择圆形并单击绘制图像时,将调用 drawCircle()函数,对于其他值也是如此。您可以通过保存选择元素来知道选定的项目。

  var mySelect = document.getElementById('MySelect'); 
var selected = mySelect.options [mySelect.selectedIndex] .text;

然后在draw函数中添加它然后决定做什么:

  function draw(){
var mySelect = document.getElementById('MySelect');
var selected = mySelect.options [mySelect.selectedIndex] .text;
if(selected ==='Circle'){
drawCircle();
}
.........
}



<可能有更多可行的解决方案。


I have a html page with select combo box.

<select id="mySelect" name="Geometrical Figures">
  <option>Circle</option>
  <option>Triangle</option>
  <option>Square</option>
  <option>Rectangle</option>
  <option>Polygon</option>
</select>
<button  id="imagedraw" onclick="draw()">Draw Image</button>

I have different functions to draw canvas images based on user selection

function drawcircle()
function drawrectangle()
function drawtriangle()

My query is how can I set which function to call dynamically based on user input when onclick event is executed.
Ex: When user selects circle and clicks on Draw Image, drawCircle() function would be called, similarly for other values.

解决方案

You can know the selected item by saving the Select element.

var mySelect = document.getElementById('MySelect');
var selected = mySelect.options[mySelect.selectedIndex].text;

Then in the draw function you can add that and then decide what to do:

function draw(){
     var mySelect = document.getElementById('MySelect');
     var selected = mySelect.options[mySelect.selectedIndex].text;
     if(selected === 'Circle'){
          drawCircle();
      }
 .........
}

There may be more viable solutions.

这篇关于根据html选择值调用不同的javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆