我很好地掌握了javascript,这有助于我操纵和制作我的DOM动态。但我缺乏如何构建我的功能和代码的知识,所以它内部更具互动性。
在下面的示例代码中,您将如何配置代码,例如,当我添加新用户或删除一个用户时,#userContainer将自动更新。
$(document).ready(function() {
if(localStorage.myUsers){
// APPENDING USERS IN localStorage.myUsers TO #userContainer
}
$(document).on("click", "#addUser", function() {
// ADD USER TO LocalStorage.myUsers
});
$(document).on("click", "#deleteUser", function() {
// DELETE $(this) USER FROM localStorage.myUsers
});
}); // END OF document.ready
答案 0 :(得分:0)
您可以使用以下最佳的javascript结构
'use strict'
var js = (function(){
var TestUsers = function(){
// APPENDING USERS IN localStorage.myUsers TO #userContainer
};
var AddUsers = function(){
$(document).on("click", "#addUser", function() {
// ADD USER TO LocalStorage.myUsers
});
};
var DeleteUsers = function(){
$(document).on("click", "#deleteUser", function() {
// DELETE $(this) USER FROM localStorage.myUsers
});
}
return {
InIt : function(){
TestUsers();
AddUsers();
DeleteUsers();
}
}
})();
$(function)(){
js.InIt();
}
有关更多详细信息,请访问: Javascript Code Organization - The Object Literal
答案 1 :(得分:-2)
只要您生成html的函数不是太重,这就是一种方法:
$(document).ready(function() {
if(localStorage.myUsers){
PopulateUserContainer();
}
$(document).on("click", "#addUser", function() {
// ADD USER TO LocalStorage.myUsers
PopulateUserContainer();
});
$(document).on("click", "#deleteUser", function() {
// DELETE $(this) USER FROM localStorage.myUsers
PopulateUserContainer();
});
}); // END OF document.ready
function PopulateUserContainer()
{
//Clear html.
// APPENDING USERS IN localStorage.myUsers TO #userContainer
}