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

时间:2017-05-31 20:43:34

标签: javascript jquery

我真的是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[]或使用click函数从我的案例中获取数组中的特定值?

1 个答案:

答案 0 :(得分:2)

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

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>