在excel里面,单元格A的值=单元格B+单元格C,如果我改动单元格B的值,那么A的值会自动改动,在js里面如何实现?
现在的做法是
<input type=text id=txt1>
<input type=text id=txt2>
<input type=text id=txt3>$("#txt2").keyup(function(){   //简写了
   txt1 = txt2+txt3;});
$("#txt3").keyup(function(){   //简写了
   txt1 = txt2+txt3;});
貌似实现了这个功能,但是如果txt3的也是由其他的输入框经过运算而得话,那就很麻烦了,有大侠帮忙解决这个问题吗?

解决方案 »

  1.   

    写了个简单的例子
    <!doctype html><html>
    <script type="text/javascript">
    function get(id){
        return document.getElementById(id);
    }window.onload=function(){
        var txt1=get("txt1"),
            txt2=get("txt2"),
            txt3=get("txt3"),
            txt4=get("txt4");
         
        //级联更新   
        var map={};
        map["txt1"]=["txt2"];          //txt1更新会导致txt2和txt3更新,txt3必须在txt2后求值,所以……
        map["txt2"]=["txt3","txt4"];   //txt2更新会导致txt3和txt4更新
        
        //更新函数
        var mapFn={};
        mapFn["txt2"]=function(){
            txt2.value=parseFloat(txt1.value)+1;
        };
        mapFn["txt3"]=function(){
            txt3.value=parseFloat(txt1.value)+parseFloat(txt2.value);
        };
        mapFn["txt4"]=function(){
            txt4.value=parseFloat(txt2.value)*2;
        };    function updateAll(id){
            var list=map[id]||[],len=list.length;
            if(len==0) return;
            
            for(var i=0;i<len;i++){
                var id=list[i],fn=mapFn[id];
                fn(); //更新
                
                updateAll(id);  //递归更新
            }
        }
        
        txt1.onkeyup=txt2.onkeyup=txt3.onkeyup=txt4.onkeyup=function(){
            updateAll(this.id);
        };
    };
    </script>
    <div>
        <input id="txt1" type="text" value="1" />
        <input id="txt2" type="text" value="" />
        <input id="txt3" type="text" value="" />
        <input id="txt4" type="text" value="" />
    </div>
    </html>
      

  2.   

    MSDN里面有类似的例子
    http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/setExpression.htm
    你可以研究一下
    http://msdn.microsoft.com/en-us/library/ms531196(v=vs.85)用的是setExpression