javascript变量是未定义的,它是.为什么?

yos*_*ssi 3 javascript jquery

为什么我会收到this(TypeError: $h is undefined)错误?

    <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);
        }
Run Code Online (Sandbox Code Playgroud)

Den*_*ret 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"
});
Run Code Online (Sandbox Code Playgroud)