如何在营养计算器中简化我的 JS 函数?
How to simplify my JS functions in a nutrition calculator?
https://codepen.io/TBD007/pen/zYxgWbv
试图避免为每个按钮的 onclick 事件编写一个函数。目前我正在为每个 onclick 使用一个单独的函数。我很确定有一种方法可以将所有这些放入一个函数中,但我自己无法弄清楚.. 有什么想法可以简化 js 代码以计算值吗?非常感谢您的帮助!
function test() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test2() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test2").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test3() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test3").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
这是完整的片段:
var result = document.getElementById("txtResult").innerHTML;
function test() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test2() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test2").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test3() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test3").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test4() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test4").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test5() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test5").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test6() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test6").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test7() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test7").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test8() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test8").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test9() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test9").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test10() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test10").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test11() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test11").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test12() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test12").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test13() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test13").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test14() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test14").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function add() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(y) + Number(z);
}
function sub() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(z) - Number(y);
}
function clearentry() {
document.getElementById("txtResultItem").innerHTML = 0;
document.getElementById("txtResult").innerHTML = 0;
}
.main {
width: 100%;
height: 100vh;
background: linear-gradient(to right, rgba(26, 26, 43, 0.496), rgba(26, 26, 43, 0.86)), url("https://www.miss.at/wp-content/uploads/2019/11/Technik-Panne-McDonalds-muss-400.000-Euro-an-Gewinner-zahlen-1024x683.jpg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
display: flex;
justify-content: center;
align-items: center;
}
button {
height: 60px;
width: 60px;
border: 2px solid silver;
box-shadow: 2px 2px 5px black;
position: relative;
}
#txtResult {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
#txtResultItem {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
button {
height: 60px;
width: 60px;
background-size: contain;
}
#btnClearEntry {
font-family: 'Raleway';
max-height: 60px;
max-width: 60px;
}
#btn1 {
background-image: url("https://img.scoop.it/aImnklIQUA5uWH212vRoWjl72eJkfbmt4t8yenImKBVvK0kTmF0xjctABnaLJIm9");
}
#btn2 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-big-mac.png?$Nutritional_Desktop$");
}
#btn3 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hamburger.png?$Nutritional_Desktop$");
}
#btn4 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-6-chicken-mcnuggets.png?$Nutritional_Desktop$");
}
#btn5 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-crispy-caesar-chicken-mcwrap.png?$Nutritional_Desktop$");
}
#btn6 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-fries-medium.png?$Nutritional_Desktop$");
}
#btn7 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-blueberry-muffin-hero.png?$Nutritional_Desktop$");
}
#btn8 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-coca-cola.png?$Nutritional_Desktop$");
}
#btn9 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-side-caesar-salad.png?$Nutritional_Desktop$");
}
#btn10 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-egg-mcmuffin.png?$Nutritional_Desktop$");
}
#btn11 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-filet-o-fish.png?$Nutritional_Desktop$");
}
#btn12 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-quarter-pounder-cheese.png?$Nutritional_Desktop$");
}
#btn13 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-baked-apple-pie.png?$Nutritional_Desktop$");
}
#btn14 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hot-fudge-sundae.png?$Nutritional_Desktop$")
}
#logo {
background-image: url("http://www.mcdonalds.at/sites/default/files/cms/social_media/sharelogo.png");
height: 60px;
width: 60px;
border: 0px solid rgba(40, 40, 53, 0.89);
box-shadow: 2px 2px 9px black;
}
#btnClearEntry {
background: rgba(40, 40, 53, 0.79);
border: 1px solid white;
color: white;
width: 62px;
height: 62px;
box-shadow: 2px 2px 7px black;
}
#btnplus {
color: white;
background: red;
border: 1px solid silver;
font-size: 18px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#btnminus {
color: white;
background: rgba(255, 223, 15, 1);
border: 1px solid silver;
font-size: 30px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#logo {
border: 1px solid white;
}
.calculator {
box-shadow: 2px 2px 10 px rgba(0, 0, 0, 0.648);
padding: 5px;
}
button:hover {
position: relative;
}
button[aria-label]:hover:after {
content: attr(aria-label);
padding: 4px 8px;
position: absolute;
left: 0;
top: 100%;
white-space: nowrap;
z-index: 20;
background: red;
color: yellow;
font-family: 'Raleway';
}
<head>
<link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="main">
<div class="calculator">
<table>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:20px;" id="txtResult" readonly="readonly"></div>
</td>
</tr>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:16px;" id="txtResultItem"></div>
</td>
</tr>
<tr>
<td id="test" value="475"><button onclick="test()" id="btn1" aria-label="Happy Meal"></button></td>
<td id="test2" value="540">
<button onclick="test2()" id="btn2" aria-label="Big Mac"></button>
</td>
<td><a href="https://www.mcdonalds.at/kalorienrechner" target="_blank"><button aria-label="All Products" id="logo" ></button></a></td>
<td><button id="btnClearEntry" onclick="clearentry()">CE</button></td>
</tr>
<tr>
<td id="test3" value="200"><button onclick="test3()" id="btn3" aria-label="Hamburger"></button></td>
<td id="test4" value="250"><button onclick="test4()" id="btn4" aria-label="6 Chicken Nuggets"></button></td>
<td id="test5" value="570"><button onclick="test5()" id="btn5" aria-label="Crispy Chicken Wrap"></button></td>
<td><button id="btnplus" onclick="add()"><b>+</b></button></td>
</tr>
<tr>
<td id="test6" value="350"><button onclick="test6()" id="btn6" aria-label="Big Fries"></button></td>
<td id="test7" value="430"><button onclick="test7()" id="btn7" aria-label="Blueberry Muffin"></button></td>
<td id="test8" value="190"><button onclick="test8()" id="btn8" aria-label="Coke"></button></td>
<td><button id="btnminus" onclick="sub()"><b>-</b></button></td>
</tr>
<tr>
<td id="test9" value="360"><button onclick="test9()" id="btn9" aria-label="Cesars salad"></button></td>
<td id="test10" value="290"><button onclick="test10()" id="btn10" aria-label="Egg McMuffin"></button></td>
<td id="test11" value="360"><button onclick="test11()" id="btn11" aria-label="Fish Mac"></button></td>
<td id="test12" value="490"><button onclick="test12()" id="btn12" aria-label="Royal with Cheese"></button></td>
</tr>
<tr>
<td></td>
<td id="test13" value="270"><button onclick="test13()" id="btn13" aria-label="Baked Apple Pie"></button></td>
<td id="test14" value="340"><button onclick="test14()" id="btn14" aria-label="Mc Sundae"></button></td>
<td></td>
</tr>
</table>
</div>
</div>
</body>
你可以用这个替换所有这些功能;
function test(elementId){
var summe = document.getElementById("txtResult").innerHTML ;
var x = document.getElementById(elementId).getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
然后在您的 onClick 处理程序中执行类似
的操作
- 测试('test')
- 测试('test2')
- 测试('test3')
然后将元素的 id 作为字符串值传递给函数。
因此,您的函数中唯一的变量是您从中获取的元素的 ID x
,您可以编写一个接受此变量作为参数的函数,并在调用它时将其传递给函数
function test(id){
var summe = document.getElementById("txtResult").innerHTML ;
var x = document.getElementById(id).getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
<button onclick="test('test')">
试试这个,为带有数字 1,2,3..etc 的函数添加一个参数并传递该值并将其附加到 document.getElementById("test"+itemValue) 中。 getAttribute("value") 值。
动态传递来自点击事件的输入。
function test(itemValue){
var summe = document.getElementById("txtResult").innerHTML ;
var x=document.getElementById("test"+itemValue).getAttribute("value");
document.getElementById("txtResultItem").innerHTML=x;
}
检查下面的代码片段
function test(){
thisObj=event.target;
var summe = document.getElementById("txtResult").innerHTML ;
var x=thisObj.getAttribute("value");
document.getElementById("txtResultItem").innerHTML=x;
}
<div id="txtResult"></div>
<input type="button" value="1" onclick="test()" />
<input type="button" value="2" onclick="test()" />
<input type="button" value="3" onclick="test()" />
<div id="txtResultItem"></div>
您可以在 onclick
事件处理程序中使用 this
引用(无需传递额外的参数,例如 test3
等)
function test(item){
console.log(item.value)
}
<div><button value="1" onclick="test(this)">1</button></div>
<div><button value="2" onclick="test(this)">2</button></div>
<div><button value="3" onclick="test(this)">3</button></div>
或者您可以使用 event.target
:
function test(){
var item = event.target;
console.log(item.value)
}
<div><button value="1" onclick="test()">1</button></div>
<div><button value="2" onclick="test()">2</button></div>
<div><button value="3" onclick="test()">3</button></div>
您可以使用一个函数,传入要用作 var x
的元素的 ID。
Javascript
function test_reuse(elid){
var summe = document.getElementById("txtResult").innerHTML ;
var x=document.getElementById(elid).getAttribute("value");
document.getElementById("txtResultItem").innerHTML=x;
}
样本HTML元素
<td id="test3" value="200"><button onclick="test_reuse('test3')" id="btn3" aria-label="Hamburger"></button></td>
您可以让您的按钮在点击时触发一个事件,并根据该事件获取相应按钮的 ID 并相应地更新 UI。
<td id="test3" value="200"><button onclick="test_general(event)" id="btn3" aria-label="Hamburger"></button></td>
....
//JS
function test_general(event){
var button_id = event.target.id
// DO SOMETHING NOW THAT YOU HAVE THE ID OF BUTTON
console.log(button_id)
}
几点建议:
- 在元素上添加
id
可以帮助您唯一地识别,但跟踪起来会变得很庞大。使用 类 或复合选择器来实现这一点。
- 在标记上添加
onClick
会造成安全威胁,因为任何人都可以检查您的元素并查看发生了什么。使用 .addEventListener
将封装代码并保持标记干净。
- 按钮/处理程序的 1-1 映射有点矫枉过正。您可以将任何元信息添加为
data-
标记的一部分,并且可以检索以进行处理。
以下是更新后的代码:https://codepen.io/TBD007/pen/zYxgWbv 解决了上面的指针。
请注意,我在 HTML
中添加了 data-number
属性
这是一个较短的版本
我使用以下技巧
- 不显眼的事件处理程序
- 保存名称和值的对象
- DOM 操纵(抱歉我对运算符偷懒了)
- 从 link 中删除了按钮并使用图像代替徽标
const buttons = {
"Happy Meal": 475,
"Big Mac": 540,
"Hamburger": 200,
"6 Chicken Nuggets": 250,
"Crispy Chicken Wrap": 570,
"Big Fries": 350,
"Blueberry Muffin": 430,
"Coke": 190,
"Cesars salad": 360,
"Egg McMuffin": 290,
"Fish Mac": 360,
"Royal with Cheese": 490,
"Baked Apple Pie": 270,
"Mc Sundae": 340
}
const operators = [
'<a href="https://www.mcdonalds.at/kalorienrechner" target="_blank"><img src="http://www.mcdonalds.at/sites/default/files/cms/social_media/sharelogo.png" aria-label="All Products" id="logo" ></img></a>',
'<button id="btnClearEntry" onclick="clearentry()">CE</button>',
'<button id="btnplus" onclick="add()"><b>+</b></button>',
'<button id="btnminus" onclick="sub()"><b>-</b></button>'
]
const tb = document.querySelector(".calculator table tbody");
let cnt = 0;
let tr = document.createElement("tr");
for (let but in buttons) {
cnt++;
td = document.createElement("td");
td.innerHTML = '<button type="button" id="btn' + cnt + '" aria-label="' + but + '" value="' + buttons[but] + '"></button>';
tr.appendChild(td)
if (cnt % 3 === 0) {
if (operators.length > 0) {
td = document.createElement("td");
td.innerHTML = operators.shift()
}
tr.appendChild(td);
tb.appendChild(tr);
tr = document.createElement("tr");
}
}
tb.appendChild(tr);
tb.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.type && tgt.type === "button") {
document.getElementById("txtResultItem").innerHTML = tgt.value;
}
});
function add() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(y) + Number(z);
}
function sub() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(z) - Number(y);
}
function clearentry() {
document.getElementById("txtResultItem").innerHTML = 0;
document.getElementById("txtResult").innerHTML = 0;
}
.main {
width: 100%;
height: 100vh;
background: linear-gradient(to right, rgba(26, 26, 43, 0.496), rgba(26, 26, 43, 0.86)), url("https://www.miss.at/wp-content/uploads/2019/11/Technik-Panne-McDonalds-muss-400.000-Euro-an-Gewinner-zahlen-1024x683.jpg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
display: flex;
justify-content: center;
align-items: center;
}
button {
height: 60px;
width: 60px;
border: 2px solid silver;
box-shadow: 2px 2px 5px black;
position: relative;
}
#txtResult {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
#txtResultItem {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
button {
height: 60px;
width: 60px;
background-size: contain;
}
#btnClearEntry {
font-family: 'Raleway';
max-height: 60px;
max-width: 60px;
}
#btn1 {
background-image: url("https://img.scoop.it/aImnklIQUA5uWH212vRoWjl72eJkfbmt4t8yenImKBVvK0kTmF0xjctABnaLJIm9");
}
#btn2 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-big-mac.png?$Nutritional_Desktop$");
}
#btn3 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hamburger.png?$Nutritional_Desktop$");
}
#btn4 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-6-chicken-mcnuggets.png?$Nutritional_Desktop$");
}
#btn5 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-crispy-caesar-chicken-mcwrap.png?$Nutritional_Desktop$");
}
#btn6 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-fries-medium.png?$Nutritional_Desktop$");
}
#btn7 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-blueberry-muffin-hero.png?$Nutritional_Desktop$");
}
#btn8 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-coca-cola.png?$Nutritional_Desktop$");
}
#btn9 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-side-caesar-salad.png?$Nutritional_Desktop$");
}
#btn10 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-egg-mcmuffin.png?$Nutritional_Desktop$");
}
#btn11 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-filet-o-fish.png?$Nutritional_Desktop$");
}
#btn12 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-quarter-pounder-cheese.png?$Nutritional_Desktop$");
}
#btn13 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-baked-apple-pie.png?$Nutritional_Desktop$");
}
#btn14 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hot-fudge-sundae.png?$Nutritional_Desktop$")
}
#logo {
height: 60px;
width: 60px;
border: 0px solid rgba(40, 40, 53, 0.89);
box-shadow: 2px 2px 9px black;
}
#btnClearEntry {
background: rgba(40, 40, 53, 0.79);
border: 1px solid white;
color: white;
width: 62px;
height: 62px;
box-shadow: 2px 2px 7px black;
}
#btnplus {
color: white;
background: red;
border: 1px solid silver;
font-size: 18px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#btnminus {
color: white;
background: rgba(255, 223, 15, 1);
border: 1px solid silver;
font-size: 30px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#logo {
border: 1px solid white;
}
.calculator {
box-shadow: 2px 2px 10 px rgba(0, 0, 0, 0.648);
padding: 5px;
}
button:hover {
position: relative;
}
button[aria-label]:hover:after {
content: attr(aria-label);
padding: 4px 8px;
position: absolute;
left: 0;
top: 100%;
white-space: nowrap;
z-index: 20;
background: red;
color: yellow;
font-family: 'Raleway';
}
<head>
<link rel="stylesheet" type="text/css" href="default.css">
<link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet">
<script type="text/javascript" src="calc.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div class="main">
<div class="calculator">
<table>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:20px;" id="txtResult" readonly="readonly"></div>
</td>
</tr>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:16px;" id="txtResultItem"></div>
</td>
</tr>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
https://codepen.io/TBD007/pen/zYxgWbv
试图避免为每个按钮的 onclick 事件编写一个函数。目前我正在为每个 onclick 使用一个单独的函数。我很确定有一种方法可以将所有这些放入一个函数中,但我自己无法弄清楚.. 有什么想法可以简化 js 代码以计算值吗?非常感谢您的帮助!
function test() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test2() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test2").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test3() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test3").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
这是完整的片段:
var result = document.getElementById("txtResult").innerHTML;
function test() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test2() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test2").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test3() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test3").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test4() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test4").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test5() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test5").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test6() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test6").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test7() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test7").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test8() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test8").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test9() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test9").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test10() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test10").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test11() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test11").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test12() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test12").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test13() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test13").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function test14() {
var summe = document.getElementById("txtResult").innerHTML;
var x = document.getElementById("test14").getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
function add() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(y) + Number(z);
}
function sub() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(z) - Number(y);
}
function clearentry() {
document.getElementById("txtResultItem").innerHTML = 0;
document.getElementById("txtResult").innerHTML = 0;
}
.main {
width: 100%;
height: 100vh;
background: linear-gradient(to right, rgba(26, 26, 43, 0.496), rgba(26, 26, 43, 0.86)), url("https://www.miss.at/wp-content/uploads/2019/11/Technik-Panne-McDonalds-muss-400.000-Euro-an-Gewinner-zahlen-1024x683.jpg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
display: flex;
justify-content: center;
align-items: center;
}
button {
height: 60px;
width: 60px;
border: 2px solid silver;
box-shadow: 2px 2px 5px black;
position: relative;
}
#txtResult {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
#txtResultItem {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
button {
height: 60px;
width: 60px;
background-size: contain;
}
#btnClearEntry {
font-family: 'Raleway';
max-height: 60px;
max-width: 60px;
}
#btn1 {
background-image: url("https://img.scoop.it/aImnklIQUA5uWH212vRoWjl72eJkfbmt4t8yenImKBVvK0kTmF0xjctABnaLJIm9");
}
#btn2 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-big-mac.png?$Nutritional_Desktop$");
}
#btn3 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hamburger.png?$Nutritional_Desktop$");
}
#btn4 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-6-chicken-mcnuggets.png?$Nutritional_Desktop$");
}
#btn5 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-crispy-caesar-chicken-mcwrap.png?$Nutritional_Desktop$");
}
#btn6 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-fries-medium.png?$Nutritional_Desktop$");
}
#btn7 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-blueberry-muffin-hero.png?$Nutritional_Desktop$");
}
#btn8 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-coca-cola.png?$Nutritional_Desktop$");
}
#btn9 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-side-caesar-salad.png?$Nutritional_Desktop$");
}
#btn10 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-egg-mcmuffin.png?$Nutritional_Desktop$");
}
#btn11 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-filet-o-fish.png?$Nutritional_Desktop$");
}
#btn12 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-quarter-pounder-cheese.png?$Nutritional_Desktop$");
}
#btn13 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-baked-apple-pie.png?$Nutritional_Desktop$");
}
#btn14 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hot-fudge-sundae.png?$Nutritional_Desktop$")
}
#logo {
background-image: url("http://www.mcdonalds.at/sites/default/files/cms/social_media/sharelogo.png");
height: 60px;
width: 60px;
border: 0px solid rgba(40, 40, 53, 0.89);
box-shadow: 2px 2px 9px black;
}
#btnClearEntry {
background: rgba(40, 40, 53, 0.79);
border: 1px solid white;
color: white;
width: 62px;
height: 62px;
box-shadow: 2px 2px 7px black;
}
#btnplus {
color: white;
background: red;
border: 1px solid silver;
font-size: 18px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#btnminus {
color: white;
background: rgba(255, 223, 15, 1);
border: 1px solid silver;
font-size: 30px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#logo {
border: 1px solid white;
}
.calculator {
box-shadow: 2px 2px 10 px rgba(0, 0, 0, 0.648);
padding: 5px;
}
button:hover {
position: relative;
}
button[aria-label]:hover:after {
content: attr(aria-label);
padding: 4px 8px;
position: absolute;
left: 0;
top: 100%;
white-space: nowrap;
z-index: 20;
background: red;
color: yellow;
font-family: 'Raleway';
}
<head>
<link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="main">
<div class="calculator">
<table>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:20px;" id="txtResult" readonly="readonly"></div>
</td>
</tr>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:16px;" id="txtResultItem"></div>
</td>
</tr>
<tr>
<td id="test" value="475"><button onclick="test()" id="btn1" aria-label="Happy Meal"></button></td>
<td id="test2" value="540">
<button onclick="test2()" id="btn2" aria-label="Big Mac"></button>
</td>
<td><a href="https://www.mcdonalds.at/kalorienrechner" target="_blank"><button aria-label="All Products" id="logo" ></button></a></td>
<td><button id="btnClearEntry" onclick="clearentry()">CE</button></td>
</tr>
<tr>
<td id="test3" value="200"><button onclick="test3()" id="btn3" aria-label="Hamburger"></button></td>
<td id="test4" value="250"><button onclick="test4()" id="btn4" aria-label="6 Chicken Nuggets"></button></td>
<td id="test5" value="570"><button onclick="test5()" id="btn5" aria-label="Crispy Chicken Wrap"></button></td>
<td><button id="btnplus" onclick="add()"><b>+</b></button></td>
</tr>
<tr>
<td id="test6" value="350"><button onclick="test6()" id="btn6" aria-label="Big Fries"></button></td>
<td id="test7" value="430"><button onclick="test7()" id="btn7" aria-label="Blueberry Muffin"></button></td>
<td id="test8" value="190"><button onclick="test8()" id="btn8" aria-label="Coke"></button></td>
<td><button id="btnminus" onclick="sub()"><b>-</b></button></td>
</tr>
<tr>
<td id="test9" value="360"><button onclick="test9()" id="btn9" aria-label="Cesars salad"></button></td>
<td id="test10" value="290"><button onclick="test10()" id="btn10" aria-label="Egg McMuffin"></button></td>
<td id="test11" value="360"><button onclick="test11()" id="btn11" aria-label="Fish Mac"></button></td>
<td id="test12" value="490"><button onclick="test12()" id="btn12" aria-label="Royal with Cheese"></button></td>
</tr>
<tr>
<td></td>
<td id="test13" value="270"><button onclick="test13()" id="btn13" aria-label="Baked Apple Pie"></button></td>
<td id="test14" value="340"><button onclick="test14()" id="btn14" aria-label="Mc Sundae"></button></td>
<td></td>
</tr>
</table>
</div>
</div>
</body>
你可以用这个替换所有这些功能;
function test(elementId){
var summe = document.getElementById("txtResult").innerHTML ;
var x = document.getElementById(elementId).getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
然后在您的 onClick 处理程序中执行类似
的操作- 测试('test')
- 测试('test2')
- 测试('test3')
然后将元素的 id 作为字符串值传递给函数。
因此,您的函数中唯一的变量是您从中获取的元素的 ID x
,您可以编写一个接受此变量作为参数的函数,并在调用它时将其传递给函数
function test(id){
var summe = document.getElementById("txtResult").innerHTML ;
var x = document.getElementById(id).getAttribute("value");
document.getElementById("txtResultItem").innerHTML = x;
}
<button onclick="test('test')">
试试这个,为带有数字 1,2,3..etc 的函数添加一个参数并传递该值并将其附加到 document.getElementById("test"+itemValue) 中。 getAttribute("value") 值。 动态传递来自点击事件的输入。
function test(itemValue){
var summe = document.getElementById("txtResult").innerHTML ;
var x=document.getElementById("test"+itemValue).getAttribute("value");
document.getElementById("txtResultItem").innerHTML=x;
}
检查下面的代码片段
function test(){
thisObj=event.target;
var summe = document.getElementById("txtResult").innerHTML ;
var x=thisObj.getAttribute("value");
document.getElementById("txtResultItem").innerHTML=x;
}
<div id="txtResult"></div>
<input type="button" value="1" onclick="test()" />
<input type="button" value="2" onclick="test()" />
<input type="button" value="3" onclick="test()" />
<div id="txtResultItem"></div>
您可以在 onclick
事件处理程序中使用 this
引用(无需传递额外的参数,例如 test3
等)
function test(item){
console.log(item.value)
}
<div><button value="1" onclick="test(this)">1</button></div>
<div><button value="2" onclick="test(this)">2</button></div>
<div><button value="3" onclick="test(this)">3</button></div>
或者您可以使用 event.target
:
function test(){
var item = event.target;
console.log(item.value)
}
<div><button value="1" onclick="test()">1</button></div>
<div><button value="2" onclick="test()">2</button></div>
<div><button value="3" onclick="test()">3</button></div>
您可以使用一个函数,传入要用作 var x
的元素的 ID。
Javascript
function test_reuse(elid){
var summe = document.getElementById("txtResult").innerHTML ;
var x=document.getElementById(elid).getAttribute("value");
document.getElementById("txtResultItem").innerHTML=x;
}
样本HTML元素
<td id="test3" value="200"><button onclick="test_reuse('test3')" id="btn3" aria-label="Hamburger"></button></td>
您可以让您的按钮在点击时触发一个事件,并根据该事件获取相应按钮的 ID 并相应地更新 UI。
<td id="test3" value="200"><button onclick="test_general(event)" id="btn3" aria-label="Hamburger"></button></td>
....
//JS
function test_general(event){
var button_id = event.target.id
// DO SOMETHING NOW THAT YOU HAVE THE ID OF BUTTON
console.log(button_id)
}
几点建议:
- 在元素上添加
id
可以帮助您唯一地识别,但跟踪起来会变得很庞大。使用 类 或复合选择器来实现这一点。 - 在标记上添加
onClick
会造成安全威胁,因为任何人都可以检查您的元素并查看发生了什么。使用.addEventListener
将封装代码并保持标记干净。 - 按钮/处理程序的 1-1 映射有点矫枉过正。您可以将任何元信息添加为
data-
标记的一部分,并且可以检索以进行处理。
以下是更新后的代码:https://codepen.io/TBD007/pen/zYxgWbv 解决了上面的指针。
请注意,我在 HTML
中添加了data-number
属性
这是一个较短的版本
我使用以下技巧
- 不显眼的事件处理程序
- 保存名称和值的对象
- DOM 操纵(抱歉我对运算符偷懒了)
- 从 link 中删除了按钮并使用图像代替徽标
const buttons = {
"Happy Meal": 475,
"Big Mac": 540,
"Hamburger": 200,
"6 Chicken Nuggets": 250,
"Crispy Chicken Wrap": 570,
"Big Fries": 350,
"Blueberry Muffin": 430,
"Coke": 190,
"Cesars salad": 360,
"Egg McMuffin": 290,
"Fish Mac": 360,
"Royal with Cheese": 490,
"Baked Apple Pie": 270,
"Mc Sundae": 340
}
const operators = [
'<a href="https://www.mcdonalds.at/kalorienrechner" target="_blank"><img src="http://www.mcdonalds.at/sites/default/files/cms/social_media/sharelogo.png" aria-label="All Products" id="logo" ></img></a>',
'<button id="btnClearEntry" onclick="clearentry()">CE</button>',
'<button id="btnplus" onclick="add()"><b>+</b></button>',
'<button id="btnminus" onclick="sub()"><b>-</b></button>'
]
const tb = document.querySelector(".calculator table tbody");
let cnt = 0;
let tr = document.createElement("tr");
for (let but in buttons) {
cnt++;
td = document.createElement("td");
td.innerHTML = '<button type="button" id="btn' + cnt + '" aria-label="' + but + '" value="' + buttons[but] + '"></button>';
tr.appendChild(td)
if (cnt % 3 === 0) {
if (operators.length > 0) {
td = document.createElement("td");
td.innerHTML = operators.shift()
}
tr.appendChild(td);
tb.appendChild(tr);
tr = document.createElement("tr");
}
}
tb.appendChild(tr);
tb.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.type && tgt.type === "button") {
document.getElementById("txtResultItem").innerHTML = tgt.value;
}
});
function add() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(y) + Number(z);
}
function sub() {
var y = document.getElementById("txtResultItem").innerHTML;
var z = document.getElementById("txtResult").innerHTML;
document.getElementById("txtResult").innerHTML = Number(z) - Number(y);
}
function clearentry() {
document.getElementById("txtResultItem").innerHTML = 0;
document.getElementById("txtResult").innerHTML = 0;
}
.main {
width: 100%;
height: 100vh;
background: linear-gradient(to right, rgba(26, 26, 43, 0.496), rgba(26, 26, 43, 0.86)), url("https://www.miss.at/wp-content/uploads/2019/11/Technik-Panne-McDonalds-muss-400.000-Euro-an-Gewinner-zahlen-1024x683.jpg");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
display: flex;
justify-content: center;
align-items: center;
}
button {
height: 60px;
width: 60px;
border: 2px solid silver;
box-shadow: 2px 2px 5px black;
position: relative;
}
#txtResult {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
#txtResultItem {
width: 257px;
height: 40px;
text-align: right;
background: rgba(40, 40, 53, 0.69);
margin-bottom: 5px;
box-shadow: inset -2px -2px 1px gray;
}
button {
height: 60px;
width: 60px;
background-size: contain;
}
#btnClearEntry {
font-family: 'Raleway';
max-height: 60px;
max-width: 60px;
}
#btn1 {
background-image: url("https://img.scoop.it/aImnklIQUA5uWH212vRoWjl72eJkfbmt4t8yenImKBVvK0kTmF0xjctABnaLJIm9");
}
#btn2 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-big-mac.png?$Nutritional_Desktop$");
}
#btn3 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hamburger.png?$Nutritional_Desktop$");
}
#btn4 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-6-chicken-mcnuggets.png?$Nutritional_Desktop$");
}
#btn5 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-crispy-caesar-chicken-mcwrap.png?$Nutritional_Desktop$");
}
#btn6 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-fries-medium.png?$Nutritional_Desktop$");
}
#btn7 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-blueberry-muffin-hero.png?$Nutritional_Desktop$");
}
#btn8 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-coca-cola.png?$Nutritional_Desktop$");
}
#btn9 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-side-caesar-salad.png?$Nutritional_Desktop$");
}
#btn10 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-egg-mcmuffin.png?$Nutritional_Desktop$");
}
#btn11 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-filet-o-fish.png?$Nutritional_Desktop$");
}
#btn12 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-quarter-pounder-cheese.png?$Nutritional_Desktop$");
}
#btn13 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-baked-apple-pie.png?$Nutritional_Desktop$");
}
#btn14 {
background-image: url("https://www.mcdonalds.com/is/image/content/dam/ca/nfl/web/nutrition/products/nutrition/en/mcdonalds-hot-fudge-sundae.png?$Nutritional_Desktop$")
}
#logo {
height: 60px;
width: 60px;
border: 0px solid rgba(40, 40, 53, 0.89);
box-shadow: 2px 2px 9px black;
}
#btnClearEntry {
background: rgba(40, 40, 53, 0.79);
border: 1px solid white;
color: white;
width: 62px;
height: 62px;
box-shadow: 2px 2px 7px black;
}
#btnplus {
color: white;
background: red;
border: 1px solid silver;
font-size: 18px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#btnminus {
color: white;
background: rgba(255, 223, 15, 1);
border: 1px solid silver;
font-size: 30px;
width: 60px;
height: 60px;
box-shadow: 2px 2px 7px black;
}
#logo {
border: 1px solid white;
}
.calculator {
box-shadow: 2px 2px 10 px rgba(0, 0, 0, 0.648);
padding: 5px;
}
button:hover {
position: relative;
}
button[aria-label]:hover:after {
content: attr(aria-label);
padding: 4px 8px;
position: absolute;
left: 0;
top: 100%;
white-space: nowrap;
z-index: 20;
background: red;
color: yellow;
font-family: 'Raleway';
}
<head>
<link rel="stylesheet" type="text/css" href="default.css">
<link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet">
<script type="text/javascript" src="calc.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<div class="main">
<div class="calculator">
<table>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:20px;" id="txtResult" readonly="readonly"></div>
</td>
</tr>
<tr>
<td colspan="4">
<div style="color:white; font-family:sans-serif;font-size:16px;" id="txtResultItem"></div>
</td>
</tr>
<tbody>
</tbody>
</table>
</div>
</div>
</body>