2013-12-12 42 views
1

所以我问这个问题之前,并得到了答案,但仍然没有工作,我改变了一下代码,基本上我想选择一个onchange()事件取决于函数正在运行。所以我有下面的代码,但它没有做任何事情,下面的onchange会触发一个checkVal()函数,并且在这个函数中我想说如果某个函数在页面上运行,例如。 updatebrand(),然后运行onchange事件updatestyle(),我知道我没有做这个权利:根据功能选择一个特定的onchange事件

<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在两个函数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"; 
?> 

回答

0

退房this working fiddle

注: 它真的不好的做法,在HTML和内嵌的JavaScript使用大写字母。这就是为什么我转换为addEventListener()的呼叫。

+0

谢谢我试过你的代码。我怎么会这样做,因为当页面加载时,它应该自动运行updatebrand()函数,这意味着onchange()应该触发updatestyle()。加载后,如果用户进行更改,则应触发updatenewbrand()。 – niceguy

+0

我认为你需要再次尝试清楚地定义你的问题,包括你定义的每个功能都打算做什么。否则,我们不得不在暗处刺伤 – srquinn

+0

是的,我没有做正确的事情。所以基本上当页面加载时,默认情况下运行UpdateBrand(),在这个函数内部驻留函数UpdateStyle()。现在,UpdateBrand()有一个包含2个选项的下拉菜单,只要用户通过选择选项进行更改,Onchange会触发函数UpdatenewBrand(),并且在此函数中驻留UpdatenewStyle()。现在,如果选择UpdatenewBrand(),我希望我的其他Onchange选择UpdatenewStyle()。 – niceguy

0

如果我的理解正确,我认为实现这一目标的最佳方法是在每个正在运行的函数访问的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>