我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
当前回答
过度使用链条。
看到这个:
this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
解释
其他回答
缺陷:使用循环而不是选择器。
如果你发现自己在寻找jQuery '。每个方法迭代DOM元素,问问自己是否可以使用选择器来获取元素。
关于jQuery选择器的更多信息: http://docs.jquery.com/Selectors
缺点:没有使用Firebug这样的工具
Firebug实际上就是为这种调试而设计的。如果您打算在DOM中使用Javascript,则需要像Firebug这样的好工具来提供可见性。
有关Firebug的更多信息: http://getfirebug.com/
其他很棒的想法都在这一期的多态播客中: (jQuery秘密与戴夫沃德) http://polymorphicpodcast.com/shows/jquery/
过度使用链条。
看到这个:
this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
解释
没有意识到性能受到了影响,并且过度使用选择器而不是将它们分配给局部变量。例如:-
$('#button').click(function() {
$('#label').method();
$('#label').method2();
$('#label').css('background-color', 'red');
});
而不是:
$('#button').click(function() {
var $label = $('#label');
$label.method();
$label.method2();
$label.css('background-color', 'red');
});
或者更好的链接:-
$('#button').click(function() {
$("#label").method().method2().css("background-color", "red");
});
当我意识到调用栈是如何工作的时候,我发现这是一个具有启发性的时刻。
编辑:在评论中加入建议。
误解在正确的上下文中使用此标识符。例如:
$( "#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.
})
});
我的意见)
通常,使用jquery意味着你不必一直担心DOM元素。你可以这样写- $('div.mine'). addclass ('someClass')。Bind ('click', function(){alert('lalala')}) -这段代码将执行而不会抛出任何错误。
在某些情况下,这是有用的,在某些情况下-根本不是,但这是一个事实,jquery倾向于,嗯,空匹配友好。但是,如果试图将replaceWith与不属于文档的元素一起使用,则会抛出错误。我觉得这是违反直觉的。
另一个陷阱是,在我看来,由prevAll()方法返回的节点顺序- $('<div><span class="A"/><span class="B"/><span class="C"/><span class="D"/></div>').find('span:last-child').prevAll()。其实没什么大不了的,但我们应该记住这个事实。