简体   繁体   English

onchange function

[英]onchange function

I am trying to create a function to run when a select option is changed.我正在尝试创建一个 function 以在 select 选项更改时运行。 In my select menu i have;在我的 select 菜单中;

    <form id="frame">
       <select id="frame_color" onchange="fChange()">
           <option value="0">Polished Black</option>
           <option value="1">Grey</option>
       </select>
     </form>

The only thing that I want the fChange() function to do is update the variable that is holding the options value with the onchange value.我想让 fChange() function 做的唯一一件事就是用 onchange 值更新保存选项值的变量。 So, the variable in the function fChange starts off by holding the value "0", and when I change it to "Grey" I want the variable to update to "1".因此,function fChange 中的变量从保持值“0”开始,当我将其更改为“灰色”时,我希望变量更新为“1”。 I am having a hard time figuring out how to code the function properly.我很难弄清楚如何正确编码 function。 Any suggestions?有什么建议么?

following get the selected option value...以下获取选定的选项值...

function fChange()
{
  var val = $("#frame_color").val();
}
fChange = function(){
    var value = document.getElementById("frame_color").value;
    alert(value);
}

on jQuery:在 jQuery 上:

$(function(){
    $('#frame_color').on('change',function(){
        your_variable = $(this).val()
    });
});

for non-jQuery, a quick way to do it is:对于非 jQuery,一个快速的方法是:

document.getElementById('frame_color').onchange = function(e){
    your_variable = e.target.value;
}​

also, you might want to look at addEventListener for standards-compliant browsers, and attachEvent for IE6-8另外,您可能想查看符合标准的浏览器的addEventListener和 IE6-8 的attachEvent

try this, which is jQuery试试这个,这是 jQuery

<script type="text/javascript">

    $(document).ready(function () {
               $('#frame_color').change(function(){
                     // your code should be here
               });
        });

</script>
var variable = 0;
function fChange()
{
var val = document.getElementById("frame_color").value;
variable = val;
}



<form id="frame">
       <select id="frame_color" onchange="fChange()">
           <option value="0">Polished Black</option>
           <option value="1">Grey</option>
       </select>
     </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM