写在前面
本人并不是专业从事H5开发。
因此本系列做法,请辩证看待。
UI管理
要达到的目标:
- 每个UI单独一个html文件,定义界面
- 每个UI单独一个js文件,编写界面逻辑
- UI变化,浏览器不要请求新URL(即浏览器要像APP那样切换界面)。
步骤1 - 定义主界面
<body onload="main()">
<div id="stage">
<div id="login_ui"></div>
<div id="lobby_ui"></div>
<div id="room_ui"></div>
</div>
</body>
如上,定义了3个DIV。分别动态加载 登录界面、大厅界面、房间界面。
步骤2 - 定义UI界面
<table align="center">
<tr>
<td><label for="txtaccount">账 号:</label></td>
<td><input type="text" id="txtaccount" value="test" /></td>
</tr>
<tr>
<td><label for="txtpassword">密 码:</label></td>
<td><input type="password" id="txtpassword" value="123" /></td>
</tr>
</table>
<br />
<button id="btnlogin" type="button">点击登录</button>
如,login_ui.html文件为登录界面,内容是上述定义。
步骤3 - 加载UI界面
$('#login_ui').load('login_ui.html', function() {})
如,通过jquery
库动态加载界面到DIV中。
步骤4 - 显示UI界面
$("#stage div").each(function() {
$(this).hide()
})
$('#login_ui').show()
如,通过jquery
库,先隐藏所有DIV,再显示登录界面。
以上。
总结
通过这种方法,可以让UI单独在一个文件中定义。
即,每个UI对应2个文件 :
xxx_ui.html
负责定义UI界面
xxx_ui.js
负责编写UI的具体逻辑
这样,使得JS UI编程,符合MVC设计模式。