如何在此JavaScript中更简单?

时间:2018-09-12 13:31:34

标签: javascript

我正在尝试创建一个Js来搜索和过滤JSON中的项目

所以我在“表单”中使用了很多单选,结果将是[X,X,X,X,X,X]

我将设置50个标签x 3(选择),我会感觉我的功能会很大。

我可以通过什么方法来简化功能?

function myFunction() {
  var elements1 = document.getElementsByName("chair"),
    elements2 = document.getElementsByName("car"),
    elements3 = document.getElementsByName("house"),
    elements4 = document.getElementsByName("tree"),
    elements5 = document.getElementsByName("flower"),
    elements6 = document.getElementsByName("grass");
  var i;
  for (var a = "", i = elements1.length; i--;) {
    if (elements1[i].checked) {
      var a = elements1[i].value;
      break;
    }
  };
  for (var b = "", i = elements2.length; i--;) {
    if (elements2[i].checked) {
      var b = elements2[i].value;
      break;
    }
  };
  for (var c = "", i = elements3.length; i--;) {
    if (elements3[i].checked) {
      var c = elements3[i].value;
      break;
    }
  };
  for (var d = "", i = elements4.length; i--;) {
    if (elements4[i].checked) {
      var d = elements4[i].value;
      break;
    }
  };
  for (var e = "", i = elements5.length; i--;) {
    if (elements5[i].checked) {
      var e = elements5[i].value;
      break;
    }
  };
  for (var f = "", i = elements6.length; i--;) {
    if (elements6[i].checked) {
      var f = elements6[i].value;
      break;
    }
  };
  var o2 = document.getElementById("output2");
  o2.value = "[" + a + "," + b + "," + c + "," + d + "," + e + "," + f + "]";
  o2.innerHTML = o2.value;
}
<form><input type="radio" id="chair1" name="chair" class="chair" value="1">
  <input type="radio" id="chair0" name="chair" class="chair" value="0" checked>
  <input type="radio" id="chair-1" name="chair" class="chair" value="-1">
  <input type="radio" id="car1" name="car" class="car" value="1">
  <input type="radio" id="car0" name="car" class="car" value="0" checked>
  <input type="radio" id="car-1" name="car" class="car" value="-1">
  <input type="radio" id="house1" name="house" class="house" value="1">
  <input type="radio" id="house0" name="house" class="house" value="0" checked>
  <input type="radio" id="house-1" name="house" class="house" value="-1">
  <input type="radio" id="tree1" name="tree" class="tree" value="1">
  <input type="radio" id="tree0" name="tree" class="tree" value="0" checked>
  <input type="radio" id="tree-1" name="tree" class="tree" value="-1">
  <input type="radio" id="flower1" name="flower" class="flower" value="1">
  <input type="radio" id="flower0" name="flower" class="flower" value="0" checked>
  <input type="radio" id="flower-1" name="flower" class="flower" value="-1">
  <input type="radio" id="grass1" name="grass" class="grass" value="1">
  <input type="radio" id="grass0" name="grass" class="grass" value="0" checked>
  <input type="radio" id="grass-1" name="grass" class="grass" value="-1">
  <div> <input type="button" value="Search" id="filter" onclick="myFunction()" /> </div>
</form>
<div id="output2"></div>

5 个答案:

答案 0 :(得分:0)

使用document.querySelector()根据元素名称直接选择选中的单选按钮的值。

function myFunction() {
  var chair = document.querySelector('input[name="chair"]:checked').value;
  var car = document.querySelector('input[name="car"]:checked').value;
  var house = document.querySelector('input[name="house"]:checked').value;
  var tree = document.querySelector('input[name="tree"]:checked').value;
  var flower = document.querySelector('input[name="flower"]:checked').value;
  var grass = document.querySelector('input[name="grass"]:checked').value;

  var o2 = document.getElementById("output2");
  o2.value = "[" + chair + "," + car + "," + house + "," + tree + "," + flower + "," + grass + "]";
  o2.innerHTML = o2.value;
}

答案 1 :(得分:0)

使用数组!

function myFunction() {
    var elem_ids = [ "chair", "car", "house", "tree", "flower", "grass"];
    var elems = elem_ids.map(id => document.getElementById(id));
    var elems_check_values = elems.map(el => {
        // el is kind of an array so
        for(var i = 0; i < el.length; ++i)
            if(el[i].checked)
                return el[i].value;
        return undefined;
    }).filter(value => value == undefined) // to filter undefined values;

  var output = "[" + elems_check_values.join(",") + "]";
  var o2 = document.getElementById("output2");
  o2.innerHTML = output
}

答案 2 :(得分:0)

提供表单ID,您可以将其称为对象。

function myFunction() {

    var form = document.getElementById("myForm");
    var parts = [
        form.chair.value,
        form.car.value,
        form.house.value,
        form.tree.value,
        form.flower.value,
        form.grass.value
    ];

    var o2 = document.getElementById("output2");
    o2.innerHTML = '[' + parts.join(',') + ']';
}

这是使用FormData对象的甚至更简单的解决方案。它支持任意数量的命名表单字段,而无需在函数中实际命名它们:

function myFunction() {

    var myForm = document.getElementById('myForm');
    var formData  = new FormData(myForm);
    var parts = Array.from(formData.values());

    var o2 = document.getElementById("output2");
    o2.innerHTML = '[' + parts.join(',') + ']';
}

答案 3 :(得分:0)

您的问题可以概括为:如何以给定形式汇总所有字段的值?
该解决方案的功能只能是5行,并且适用于任何类型的任意数量的输入。 target元素的DOM模型提供了命名键(例如<form>),每个键都具有myform.inputName属性。对于单选按钮,例如value将自动提供所选单选按钮的值。

借助这些知识,您可以创建一个带有简单签名的函数,该签名采用HTMLElement形式,并包含所需值的字段名称数组,如下所示:(点击搜索按钮获取结果,并随意更改单选按钮。

myform.tree.value
function getFormValues(form, fields) {
  var result = [];
  for (var i = 0; i < fields.length; i++) {
    result.push(form[fields[i]].value);
  }
  return result;
}

document.getElementById('filter').addEventListener('click', function(e) {
  var o2 = document.getElementById("output2");
  o2.innerHTML = getFormValues(document.forms[0], ['chair','car','house','tree','flower','grass']);
});

答案 4 :(得分:0)

您需要做的就是将代码分成可重用的块。因此,提出一种获取价值的方法。这将减少大量代码。之后,您应该研究一种减少需要列出的元素的方法。最后,找到一种简单的方法来获取所有值。

因此,下面是执行此操作的代码。它使用一个辅助方法来获取元素,找到值。它比使用数组知道要查找的元素组。最后,它使用map遍历列表,因此您不必编写多个函数调用。

function getSelected (radioBtnGroup) {
   // get the elements for the radio button group
   var elms = document.getElementsByName(radioBtnGroup)
   // loop over them
   for(var i=0; i<elms.length; i++) {
     // if checked, return value and exit loop
     if (elms[i].checked) {
       return elms[i].value
     }
   }
   // if nothing is selected, return undefined
   return undefined
}

// list the groups you want to get the values for
var groups = ['rb1', 'rb2', 'rb3', 'rb4']

// call when you want to get the values
function getValues () {
  // use map to get the values of the rabio button groups.
  // map passes the index value as the first argument.
  // code is map(function(k){return getSelected(k)})
  var results = groups.map(getSelected)
  //displat the results
  console.log(results);
}

document.querySelector('#btn').addEventListener('click', getValues);
<form>
  <fieldset>
    <legend>Item 1</legend>
    <label><input type="radio" name="rb1" value="1-1"> One</label>
    <label><input type="radio" name="rb1" value="1-2"> Two</label>
    <label><input type="radio" name="rb1" value="1-3"> Three</label>
  </fieldset>
  <fieldset>
    <legend>Item 2</legend>
    <label><input type="radio" name="rb2" value="2-1"> One</label>
    <label><input type="radio" name="rb2" value="2-2"> Two</label>
    <label><input type="radio" name="rb2" value="2-3"> Three</label>
  </fieldset>
  <fieldset>
    <legend>Item 3</legend>
    <label><input type="radio" name="rb3" value="3-1"> One</label>
    <label><input type="radio" name="rb3" value="3-2"> Two</label>
    <label><input type="radio" name="rb3" value="3-3"> Three</label>
  </fieldset>
   <fieldset>
    <legend>Item 4</legend>
    <label><input type="radio" name="rb4" value="4-1"> One</label>
    <label><input type="radio" name="rb4" value="4-2"> Two</label>
    <label><input type="radio" name="rb4" value="4-3"> Three</label>
  </fieldset>
  <button type="button" id="btn">Get Results</button>
</form>

我个人不会将值存储在数组中,而是使用带有键值对的对象。

 var results = groups.reduce(function (obj, name) {
   obj[name] = getSelected(name)
   return obj
 }, {});