如何在此代码中使用输入框而不是提示? 代码是 here。
点击链接后;弹出提示并要求输入数字或Q以退出。如何将其更改为输入框?
function Stack() {
var items = [];
this.push = function(element){
items.push(element);
};
this.pop = function(){
return items.pop();
};
this.peek = function(){
return items[items.length-1];
};
this.isEmpty = function(){
return items.length == 0;
};
this.size = function(){
return items.length;
};
this.clear = function(){
items = [];
};
this.print = function(){
alert("Stack Elements are:"+items.toString());
};
}
声明堆栈对象:
var stack = new Stack();
while(1)
{
var element = prompt("Enter stack element,(q or Q to exit)", "");
if(element == 'q' || element =='Q')
{
break;
}
else
{
if(element=='*'
|| element=='+' || element=='-' || element=='/')
{
//Check if stack is empty
if(stack.isEmpty() || stack.size<2 )
{
alert("Invalid Operation, Stack is empty or size is less than 2");
}
else
{
var op1 = stack.pop();
var op2 = stack.pop();
if(element=='*')
{
var res = op1 * op2;
}
else if(element=='+')
{
var res = op1 + op2;
}
else if(element=='-')
{
var res = op1 - op2;
}
else if(element=='/')
{
var res = op1 / op2;
}
stack.push(res);
stack.print();
}
}
else
{
stack.push(element);
stack.print();
}
}
}
答案 0 :(得分:0)
尝试以下示例:
var stack = new Stack();
function Stack() {
var items = [];
this.push = function(element) {
items.push(element);
};
this.pop = function() {
return items.pop();
};
this.peek = function() {
return items[items.length - 1];
};
this.isEmpty = function() {
return items.length == 0;
};
this.size = function() {
return items.length;
};
this.clear = function() {
items = [];
};
this.print = function() {
theList.options.length = 0;
for (var i = 0; i < items.length; i++) {
var theOption = new Option(items[i]);
theList.options[theList.options.length] = theOption;
}
};
}
function pushStack(newVal) {
if (newVal == '*' || newVal == '+' || newVal == '-' || newVal == '/') {
//Check if stack is empty
if (stack.isEmpty() || stack.size < 2) {
alert("Invalid Operation, Stack is empty or size is less than 2");
} else {
var op1 = stack.pop();
var op2 = stack.pop();
if (newVal == '*') {
var res = op1 * op2;
} else if (newVal == '+') {
var res = op1 + op2;
} else if (newVal == '-') {
var res = op1 - op2;
} else if (newVal == '/') {
var res = op1 / op2;
}
stack.push(res);
}
} else {
stack.push(newVal);
}
}
function popStack() {
var popVal = stack.pop();
if (popVal == undefined)
return "Empty stack!";
else
return popVal;
}
function showStack() {
stack.print();
}
<FORM>
<INPUT type="text" name="txtPush" id="txtPush" />
<INPUT type=button value="Push" onClick='pushStack(txtPush.value); txtPush.value=""; showStack(theList);' />
<SELECT name="theList" id="theList" size=12>
<OPTION>Displays the current state of the stack!</OPTION>
</SELECT>
</FORM>