為什么這種方法實現不了,還請解答,謝謝
//方法一:
? ?function count(){
? ? ? ?var a=document.getElementById("txt1").value;
? ? ? ?var b=document.getElementById("txt2").value;
? ? ? ?var c=document.getElementById("fruit").value;
? ? ? ?var selecting=document.getElementById("select").value;
? ? ? ?switch(selecting){
? ? ? ? ? ?case "+":
? ? ? ? ? ? ? c.setAttribute("value",parseInt(a)+parseInt(b));
? ? ? ? ? ? ? break;
? ? ? ? ? ?case "-":
? ? ? ? ? ? ? ?c.setAttribute("value",parseInt(a)-parseInt(b));
? ? ? ? ? ? ? ?break;
? ? ? ? ? ?case "*":
? ? ? ? ? ? ? ?c.setAttribute("value",parseInt(a)*parseInt(b));
? ? ? ? ? ? ? ?break;
? ? ? ? ? ?case "/":
? ? ? ? ? ? ? ?c.setAttribute("value",parseInt(a)/parseInt(b));
? ? ? ? ? ? ? ?break;
? ? ? }
? ?}
為什么這種方法實現不了,還請解答,謝謝
2017-09-29
?
setAttribute的語法是element.setAttribute(attributename,attributevalue)
你定義c為 var =document.getElementById("fruit").value;
但是 加上? .value? 后c指向的就不是Element(元素),不能進行后面的c.setAttribute("value",parseInt(a)+parseInt(b));
所以得定義為var c=document.getElementById("fruit");讓c指向id為fruit的元素
2017-09-29
?var c=document.getElementById("fruit").value;這個取到的是空值,不能先取,
寫成這樣
?case "+":
? ? ? ? ? ? ? document.getElementById("fruit").setAttribute("value",parseInt(a)+parseInt(b));
? ? ? ? ? ? ? break;
就可以了,順序錯了