【问题标题】:Depending on function pick a particular onchange event根据功能选择特定的 onchange 事件
【发布时间】:2013-12-12 15:12:38
【问题描述】:

所以我之前问过这个问题并得到了答案但仍然无法正常工作,我稍微更改了代码,基本上我想根据正在运行的函数选择一个 onchange() 事件。所以我有下面的代码,但它没有做任何事情,下面的 onchange 将触发一个 checkVal() 函数,在这个函数中我想说如果某个函数在页面上运行,例如。 updatebrand() 然后运行 ​​onchange event updatestyle(),我知道我做的不对:

<SELECT NAME="choicestyle" onChange="checkVal()"; >
<option disabled="disabled" selected="selected"></option>

<SCRIPT>
function checkVal(){
    var e = document.getElementById("choicestyle");
    e.onchange = function() {
        if (e.value == "updatebrand()") { 
            updatestyle();
        } else if (e.value == "updatenewbrand") {
            updatenewstyle();
        }
    }
}
</SCRIPT>

所以我现在用这段代码编辑了顶部代码,它给出了一个错误,我将 $lastRunFunc 放在 2 个函数 updateBrand() 中的每一个中并将其设置为 0 并将其放入 updatenewBrand() 并将其设置为1,所以当发生 onchange 时,它​​应该触发 updatestyle() 和 updatenewstyle() 函数,但我不断收到对象预期错误?

<SELECT NAME="choicestyle" onChange="checkVal();">
<option disabled="disabled" selected="selected"></option>


<?
  echo "checkVal() {\n\n";

  if($lastRunFunc==0) 
  {
  echo "updatestyle();\n";
  }
  if($lastRunFunc==1)
  {
  echo "updatenewstyle();\n";
  }
  echo "}\n\n";
?>

【问题讨论】:

    标签: javascript html function triggers onchange


    【解决方案1】:

    查看this working fiddle

    注意: 在 HTML 和内联 javascript 中使用大写字母是非常糟糕的做法。这就是我转换为addEventListener() 调用的原因。

    【讨论】:

    • 谢谢我试过你的代码。我该怎么说,因为当页面加载时,它应该自动运行函数 updatebrand(),这意味着 onchange() 应该触发 updatestyle()。加载后,如果用户进行更改,则应触发 updatenewbrand()。
    • 我认为您需要再次尝试清楚地定义您的问题,包括您定义的每个功能打算做什么。否则,我们只好继续在黑暗中刺伤
    • 是的,我没有做正确的事情。所以基本上当页面加载时,默认情况下 UpdateBrand() 运行,在这个函数中驻留函数 UpdateStyle()。现在 UpdateBrand() 有一个带有 2 个选项的下拉菜单,一旦用户通过选择一个选项进行更改,Onchange 就会触发函数 UpdatenewBrand(),并且在此函数中驻留 UpdatenewStyle()。现在,如果选择了 UpdatenewBrand(),我希望我的其他 Onchange 选择 UpdatenewStyle()。
    • UpdatenewBrand() 与 UpdateBrand() 基本相同,只是其中包含 UpdatenewStyle() 而不是 updatestyle()。另外值得注意的是 Updatenewstyle 和 updatestyle 函数是带有随 Onchange 变化的选项的下拉菜单。
    【解决方案2】:

    如果我理解正确,我认为实现此目的的最佳方法是在您的 javascript 中设置一个全局变量,该变量可由正在运行的每个函数访问。然后根据全局变量,您可以相应地运行 checkVal()。

    <script>
        var lastRunFunc = "";
        function updatebrand(){
            lastRunFunc =  "updatebrand";
        }
        function updatebrand2(){
            lastRunFunc = "updatebrand2";
        }
        function checkVal(){
            if(lastRunFunc === "updatebrand"){/*do one thing*/}
            if(lastRunFunc === "updatebrand2"){/*do another thing*/}
        }
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-03
      • 2015-08-17
      • 1970-01-01
      相关资源
      最近更新 更多