小试牛刀——JS闭包

第一篇博客里已经介绍过,我的毕设是要做一个在线的流程图设计器。

第一次学习网站相关的语言,所以这两周都在学习JS的知识。

分享一下网站的界面。


左侧sidebar有三个选择:question,action,output,分别对应选择,操作和输出框。当单击任何一个选项后,弹出dialog box,询问输入对应框图内的文字,确定后显示。


网页设计有一个原则,就像MVC结构一样,表示和行为要分开,所以,在html文档中,我没有添加任何的JS语句。

这是三个选择的定义

<div class="container">
	<!-- node-palette -->
	<!-- this is the left sidebar, used to create new node -->
	<div class="sidebar node-palette" > 
		<ul>
			<li title="Drag to add new" class="jtk-surface-droppable-node jsplumb-draggable" jtk-node-type="question">
				<i class="icon-tablet"></i>
				Question
			</li>
			<li title="Drag to add new" class="jtk-surface-droppable-node jsplumb-draggable" jtk-node-type="action">
				<i class="icon-eye-open"></i>
				Action 
			</li>
			<li title="Drag to add new" class="jtk-surface-droppable-node jsplumb-draggable" jtk-node-type="output">
				<i class="icon-eye-open"></i>	
				Output  
			</li>
		</ul>
	</div>

以下相对应的JS函数。

1.首先,定义每个键的功能,在这里,alert出输入的内容。

function dispQuestionPrompt(){
	var name = prompt("enter the action name");
	if (name) {
		alert(name);

	}
}
function dispActionPrompt(){
	var name = prompt("enter the action name");
	if (name) {
		alert(name);
	}
}
function dispOutputPrompt(){
	var name = prompt("enter the output name");
	if (name) {
		alert(name);
	}
}

然后,定义调用的函数。

function chooseSidebar(){
	var sidebar = document.getElementsByClassName("sidebar node-palette");
	var tag = sidebar[0].getElementsByTagName("li");

	/*------------- js的闭包功能 --------------*/
	for(var i = 0;i < tag.length;i++)
	{
		tag[i].onclick = (function(i){
			return function(){
				switch(i){
					case 0:
						dispQuestionPrompt();
						break;
					case 1:
						dispActionPrompt();
						break;
					case 2:
						dispOutputPrompt();
						break;
				}
			}
		})(i);
	}	
}

在这里,我出现了小的问题。请教男票后,知道了JS闭包的概念。

分享一个知乎链接,有关于JS闭包的介绍https://www.zhihu.com/question/20019257


------------------------------我是分割线------------------------------------------

之前说错了,说C++的MVC架构,实际上这是不对的。



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值