遍历 Id,存储值,放入数组

Iterate through Id's, store values, put into an array

我希望能够遍历多个称为“#option1”、“#option2”等的 ID。问题在于它是交互式表单,我不知道会有多少选项。所以我需要一种方法来在用户单击(“#dothis”)时遍历 DOM 中的金额。

然后我需要获取那些选项的值,放入一个名为 arraylist 的数组中。

$("#doThis").on("click", function() {
            var optionone = $("#option1").val();
            var optiontwo = $("#option2").val();
            var optionthree = $("#option3").val();
            var optionfour = $("#option4").val();
            var optionfive = $("#option5").val();
            var arrayList = [optionone, optiontwo, optionthree,
                optionfour, optionfive];
            var decide = arrayList[Math.floor(Math.random() *
                arrayList.length)];
            $("#verdict").text(decide);
        }); // end of dothis click event

按原样使用您的代码,您可以使用选择器来选择 ID 以 'option' 开头的所有内容,就像 [id^="option"] 一样,下面是如何使用它:

   $("#doThis").on("click", function () {
        var arrayList = [];
        $('[id^="option"]').each(function (index, element) {
            arrayList.push($(element).val() );
        });

        var decide = arrayList[Math.floor(Math.random() *
            arrayList.length)];
        $("#verdict").text(decide);
    }); // end of dothis click event

正如 Andy 所说,给每个选项都一样 class。在我的示例中,它是 "option-item".

$("#doThis").on("click", function() {
  var arrayList = [];
  $('.option-item').each(function(i) {
    arrayList[i] = $(this).val();
  });
  var decide = arrayList[Math.floor(Math.random() *
      arrayList.length)];
  $("#verdict").text(decide);
});

每个值现在都存储在数组中。

fiddle.

问候蒂米