我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
当前回答
缺陷:使用循环而不是选择器。
如果你发现自己在寻找jQuery '。每个方法迭代DOM元素,问问自己是否可以使用选择器来获取元素。
关于jQuery选择器的更多信息: http://docs.jquery.com/Selectors
缺点:没有使用Firebug这样的工具
Firebug实际上就是为这种调试而设计的。如果您打算在DOM中使用Javascript,则需要像Firebug这样的好工具来提供可见性。
有关Firebug的更多信息: http://getfirebug.com/
其他很棒的想法都在这一期的多态播客中: (jQuery秘密与戴夫沃德) http://polymorphicpodcast.com/shows/jquery/
其他回答
我对JavaScript也这么说,但是jQuery, JavaScript永远不应该取代CSS。
另外,确保站点对于关闭JavaScript的人来说是可用的(现在不像以前那么重要了,但拥有一个完全可用的站点总是好的)。
误解在正确的上下文中使用此标识符。例如:
$( "#first_element").click( function( event)
{
$(this).method( ); //referring to first_element
$(".listOfElements").each( function()
{
$(this).someMethod( ); // here 'this' is not referring first_element anymore.
})
});
这里有一个解决方法的例子:
$( "#first_element").click( function( event)
{
$(this).method( ); //referring to first_element
var $that = this;
$(".listOfElements").each( function()
{
$that.someMethod( ); // here 'that' is referring to first_element still.
})
});
跟“回购人”说的差不多,但不完全一样。
在开发ASP时。NET winforms,我经常这样做
$('<%= Label1.ClientID %>');
忘记#符号。正确的形式是
$('#<%= Label1.ClientID %>');
缺陷:使用循环而不是选择器。
如果你发现自己在寻找jQuery '。每个方法迭代DOM元素,问问自己是否可以使用选择器来获取元素。
关于jQuery选择器的更多信息: http://docs.jquery.com/Selectors
缺点:没有使用Firebug这样的工具
Firebug实际上就是为这种调试而设计的。如果您打算在DOM中使用Javascript,则需要像Firebug这样的好工具来提供可见性。
有关Firebug的更多信息: http://getfirebug.com/
其他很棒的想法都在这一期的多态播客中: (jQuery秘密与戴夫沃德) http://polymorphicpodcast.com/shows/jquery/
避免创建多个相同的jQuery对象
//Avoid
function someFunc(){
$(this).fadeIn();
$(this).fadeIn();
}
//Cache the obj
function someFunc(){
var $this = $(this).fadeIn();
$this.fadeIn();
}