gpt4 book ai didi

javascript - 如何从按钮数组中获取特定数组值

转载 作者:行者123 更新时间:2023-12-01 03:35:55 26 4
gpt4 key购买 nike

我真的是 javascript 和 jquery 的新手。我现在正在制作一个计算器。

这是我的代码。

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta charset="UTF-8">
<script type="text/javascript">
var buttonname = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "+", "-", "*", "/", "C", "Enter", "="];
$(document).ready(function() {
$("button").click(function() {
// for(var i=0;i<buttonname.length;i++){
var arrayvalue = buttonname[ ? ? ? ? ? ];
var calculate = $("<p>" + arrayvalue + "</p>");
$("#result").append(calculate);
//}
});
});

</script>
</head>

<body>
<!--<textarea id="numberarea"></textarea><br>-->
<script type="text/javascript">
for (var i = 0; i < buttonname.length; i++) {
document.write("<button>" + buttonname[i] + "</button>");
if (i != 0 && (i % 4) == 0)
document.write("<br>");
}

</script>
<div id="result"></div>
</body>

</html>

在我的情况下,我应该如何使用 var arrayvalue = buttonname[] 行或单击函数来从数组中获取特定值?

最佳答案

您可以在创建按钮时向每个按钮添加属性,然后从单击处理程序的事件参数引用该属性。像这样的事情:

var buttonname = ["1","2","3","4","5","6","7","8","9","0","+","-","*","/","C","Enter","="];
$(document).ready(function(){
$("button").click(function(ev){
// for(var i=0;i<buttonname.length;i++){
var arrayvalue = buttonname[$(ev.target).attr('data-index')];
var calculate = $("<p>"+arrayvalue+"</p>");
$("#result").append(calculate);
//}
});
});

for(var i = 0; i <buttonname.length; i++){
document.write("<button data-index="+i+">"+buttonname[i]+"</button>");
if(i != 0 && (i%4) == 0)
document.write("<br>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="result"></div>

关于javascript - 如何从按钮数组中获取特定数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44294332/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com