jQuery 提示和技巧

2022-08-29 23:07:05

语法

数据存储

优化

杂项


答案 1

创建 HTML 元素并保留引用

var newDiv = $("<div />");

newDiv.attr("id", "myNewDiv").appendTo("body");

/* Now whenever I want to append the new div I created, 
   I can just reference it from the "newDiv" variable */


检查元素是否存在

if ($("#someDiv").length)
{
    // It exists...
}


编写自己的选择器

$.extend($.expr[":"], {
    over100pixels: function (e)
    {
        return $(e).height() > 100;
    }
});

$(".box:over100pixels").click(function ()
{
    alert("The element you clicked is over 100 pixels height");
});

答案 2

jQuery的data()方法是有用的,但不是众所周知的。它允许您将数据绑定到 DOM 元素,而无需修改 DOM。