2015-05-13 49 views
3

爲什麼我得到這個(TypeError: $h is undefined)錯誤?javascript變量是未定義的,它是。爲什麼?

<div style="clear: both;"> 
     <input type="button" value="test1" onclick="test1();" /> 
    </div> 
    <div id="box"></div> 
    <div id="debug"></div> 

     var $h; // also tried without "var" 
     $h = $("<div/>").css("position:absolute;top:100px;width:1px;height:1px;background:red;"); 
     function test1() { 
      var start = new Date().getTime(); 

      for (var i = 0; i < 10000; i++) { 
       $h.css("top", (i + 4)); 
       $h.appendTo("#box"); 
      } 
      var end = new Date().getTime(); 
      $("#debug").html(end - start); 
     } 
+0

哪裏是'test1'調用.... –

回答

5

css函數調用一個字符串作爲參數,返回有該名稱的樣式屬性的值。

當然沒有樣式屬性被命名爲"position:absolute;top:100px;width:1px;height:1px;background:red;",這就是爲什麼它返回undefined

你可能想要的是

var $h = $("<div/>").css({ 
    position:"absolute", 
    top:"100px", 
    width:"1px", 
    height:"1px", 
    background:"red" 
}); 
+0

絕對正確的...愚蠢的錯誤由我:)謝謝 – yossi

相關問題