我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
我开始一个项目与jQuery。
在你的jQuery项目中有哪些陷阱/错误/误解/滥用/误用?
当前回答
事件
$("selector").html($("another-selector").html());
不会克隆任何事件-你必须重新绑定它们。
根据JP的评论- clone()如果您传递true,则会重新绑定事件。
其他回答
如果你想让用户在他们的浏览器中看到html实体,使用'html'而不是'text'来注入Unicode字符串,例如:
$('p').html("Your Unicode string")
误解在正确的上下文中使用此标识符。例如:
$( "#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.
})
});
总是缓存$(this)到一个有意义的变量 特别是在.each()中
像这样
$(selector).each(function () {
var eachOf_X_loop = $(this);
})
当使用$。ajax函数对服务器的ajax请求,你应该避免使用完整的事件来处理响应数据。无论请求是否成功,它都会触发。
用成功代替完成。
请参阅文档中的Ajax事件。
避免滥用文件准备。 保持文档仅为初始化代码准备。 始终在文档外部提取函数,以便它们可以被重用。
我在doc ready语句中看到了数百行代码。丑陋,不可读,不可能维护。