html/javascript中的简单计算器
我正在尝试用html和JavaScript制作一个计算器。单击按钮后,我试图将数字插入我的div。当我这样做时,默认的“0”消失,它根本不插入任何内容html/javascript中的简单计算器,javascript,jquery,html,css,calculator,Javascript,Jquery,Html,Css,Calculator,我正在尝试用html和JavaScript制作一个计算器。单击按钮后,我试图将数字插入我的div。当我这样做时,默认的“0”消失,它根本不插入任何内容 功能复制(事件){ var newValue=event.target.value; document.querySelector(“#display”).innerHTML=newValue; } var textfield=document.querySelector(“#btn_7”); textfield.addEventListene
功能复制(事件){
var newValue=event.target.value;
document.querySelector(“#display”).innerHTML=newValue;
}
var textfield=document.querySelector(“#btn_7”);
textfield.addEventListener(“单击”,复制)代码>
0
7.
8.
9
/
4.
5.
6.
*
1.
2.
3.
-
C
0
=
+
按钮没有默认属性值
,因此在本例中使用属性textContent
我建议您使用隐藏输入来存储值,也可以使用数据属性
现在我必须为每个按钮做这个,这会占用很多行,有更好的方法吗
您可以使用函数document.querySelectorAll(选择器)
并在其上循环以绑定特定事件
功能复制(事件){
var newValue=event.target.textContent;
document.querySelector(“#display”).innerHTML=newValue;
}
Array.prototype.forEach.call(document.queryselectoral('button'),函数(b){
b、 addEventListener(“单击”,复制);
});代码>
0
7.
8.
9
/
4.
5.
6.
*
1.
2.
3.
-
C
0
=
+
这里选择value并替换display div的html。您需要做一些额外的工作来实现所需的输出
var display=$('#display');
$('.btn')。单击(函数(e){
var btn=e.目标;
display.html(btn.id);
});代码>
0
7.
8.
9
/
4.
5.
6.
*
1.
2.
3.
-
C
0
=
+
像这样试试
$(函数(){
$('button[id^=“btn”]”)。单击(函数(){
var显示;
如果($('.tmp')。长度>0){
display=$('.tmp').text();
}否则{
$(“”)。附加到(“#frame”);
显示='';
}
开关($(this).text()){
案例“C”:
显示='0';
打破
案例“=”:
显示=评估(显示);
打破
违约:
display=display.concat($(this.text());
}
$('#display')。文本(display);
$('.tmp').text((显示!='0')?显示:“”);
});
});代码>
0
7.
8.
9
/
4.
5.
6.
*
1.
2.
3.
-
C
0
=
+
实际上,您只需替换textfield.addEventListener(“单击”,复制)代码>按文档。查询选择器(#框架”)。添加文本列表器(“单击”,复制)代码>,因为事件。目标
已负责事件委派。不过,您可能需要检查类似于的内容,比如(event.target.matches(“button”))
。为什么还要添加类呢?只需使用$(“#显示”)。在(“单击”,“按钮”,函数(e){
..})代码>。此外,不应添加ID;内部文本是。只是为了区分哪些按钮需要单击处理程序。可能OP不想对其他按钮执行相同的操作。非常感谢您的解决方案非常感谢您的解决方案