我已经开始使用jQuery了。我正在努力理解如何组织代码以及如何正确使用它。目前,我使用的代码类似于:
$(document).ready(function(){
alert('all of the jquery goodness here');
$('#div1').click(function(){
/* some manipulation stuff here */
})
})在dom加载后,有没有更好的方法来加载点击处理程序?
另外,是否有一些链接可以让我获得有关jquery中代码布局的信息?我一直在看源代码,但找不到任何有用的东西..
谢谢你们
编辑
另一个简短的问题,我记得--使用类似的东西是不是很糟糕:
function clickedevent(){
$('').toggle or other random jquery function
}发布于 2011-11-13 06:55:13
我是如何做到这一点的:
// Short notation for document ready
$(function(){
// Bind the button to the method
$(".button").click(methods.handlers.clickhandler1);
});
var methods = {
handlers : {
clickhandler1 : function(){
alert("Y");
}
},
method1 : function(){
}
// ETC
};我将其分类到一个json对象中以获取一些结构,并且不会在next之后执行函数(.click(){}),因为这样您就无法找到实际绑定到已准备好的文档上的内容,更多概述。
如果您不想了解更多关于jQuery结构和制作自己的插件的信息,请阅读下面的URL http://docs.jquery.com/Plugins/Authoring
发布于 2011-11-13 08:30:53
查看Module Pattern以编写更多面向对象的javascript。关于这个话题,一个很好的读物是Douglas Crawford's 'Javascript: The Good Parts'。以下是使用jQuery的模块模式的示例:
window.MyCoolModule= (function(){
var doCoolStuff = function(){
alert("badumpumbishh")
}
var otherCoolStuff = function(){
alert("someone..moved their..mouse.. all over me");
}
var superSecretPrivateFunction = function(){
// come at me bro
}
return{
somePublicFunction: function(){
//hello, i can be called by other people
},
init: function(){
$("#div1")
.bind("click", doCoolStuff)
.bind("mouseover", otherCoolStuff)
$("#div2")
.bind("click", superSecretPrivateFunction)
}
}
}())
$(function(){
MyCoolModule.init()
})需要注意的几点:
”,doCoolStuff)’中,因此您可以一眼看到模块正在侦听的所有DOM元素。
‘
发布于 2011-11-13 06:53:40
比什么更好?这就是你想要附加它们的时候。
您可以将click处理函数本身移动到命名函数中,而不是内联它。
有时,您可以重构并使用函数生成器来创建单击处理函数,并减少代码的重复。
https://stackoverflow.com/questions/8108166
复制相似问题