jQuery1.4正式版新功能及性能测试
jQuery1.4正式版已经发布,今天来看看官方给我们的jQuery1.4的新功能以及性能测试分析。
对于jQuery常用的函数进行了大幅的性能提升
使用内部函数调用,以减少对代码库的复杂性,使jQuery1.4的性能相对于1.3.2得到了大幅的提升
方便的设置函数
jQuery1.4给很多函数加上了设置方法,可以运行一定的代码。如大家常用的以下函数:
. attr(),.css(), .attr(), .val(), .html(), .text(), .append(), .prepend(), .before(), .after(), .replaceWith(), .wrap(), .wrapInner(), .offset(), .addClass(), .removeClass(), and .toggleClass()。
以下函数可以在第二个参数变量中添加一个function的参数:
.css(), .attr(), .val(), .html(), .text(), .append(), .prepend(), .offset(), .addClass(), .removeClass(), and .toggleClass().
如以下代码:
// find all ampersands in A's and wrap with a span $('a').html(function(i,html){ return html.replace(/&/gi,'<span class="amp">&</span>'); }); // Add some information to the title of the anchors $('a[target]').attr("title", function(i,title){ return title + " (Opens in External Window)"; });
属性方法的性能以及功能的全面提升
1.、.css() 和 .attr() 性能得到了提升

2、 .attr()可以添加一个为function的参数变量
jQuery('<img src="enter.png" alt="enter your name" />') .attr("alt", function(index, value) { return "Please, " + value; });
3、.val( Function )
<input class="food" type='text' data-index="0" /> <input class="food" type='text' data-index="1" />jQuery("input:text.food").hide(); jQuery("<ul class='sortable'><li>Peanut Butter</li><li>Jelly</li></ul>") .sortable() .bind("endsort", function() { $(":text.food").val(function() { return $("ul.sortable li:eq(" + $(this).attr("data-index") + ")").text(); }); });
快速创建dom元素
现在在jQuery1.4中你可以给创建的dom元素用object的方式,同时添加事件绑定、设置css属性等,如:
jQuery("<div/>", { id: "foo", css: { height: "50px", width: "50px", color: "blue", backgroundColor: "#ccc" }, click: function() { $(this).css("backgroundColor", "red"); } }).appendTo("body");
.eq(-N), .get(-N)支持从后面往前选择
如果你想选择倒数第二个节点可以使用下面的代码:
$("div").eq(-2); $("div").get(-2);
新的方法: jQuery.proxy()
现在我们可以通过设置jQuery.proxy() 来使用this指针,如:
var obj = { name: "John", test: function() { alert( this.name ); $("#test").unbind("click", obj.test); } }; $("#test").click( jQuery.proxy( obj, "test" ) );
.bind()函数支持多个事件同时绑定
$("div.test").bind({ click: function(){ $(this).addClass("active"); }, mouseenter: function(){ $(this).addClass("inside"); }, mouseleave: function(){ $(this).removeClass("inside"); } });
新的事件监控方法`focusin`和`focusout`
jQuery1.4新增加了`focusin`和`focusout’两个事件的监听
$("form").focusout(function(event) { var tgt = event.target; if (tgt.nodeName == "INPUT" && !tgt.value) { $(tgt).after("<span>nothing here</span>"); } });
新方法:.detach()
.detach()删除一个DOM元素,但是不删除DOM的元素事件。如:
var foo = $("#foo").click(function() { // do something }); foo.detach(); // foo retains event handlers foo.appendTo("body");
新方法:unwrap()
.unwrap()可以把子节点替换掉父节点,如:
处理前html:
<body> <div> <p>annie</p> <p>davey</p> <p>stevie</p> </div> </body>处理js:
$('div').unwrap();处理后的html:
<body> <p>annie</p> <p>davey</p> <p>stevie</p> </body>
另外jQuery1.4在Ajax、选择器等在性能方面都有了很大的提升,还添加了几个新的方法。
