使用getElementsByClassName

时间:2019-06-07 16:10:24

标签: javascript

我有很多输入字段(每行3个),基本上可以完成相同的操作:

Input1 * Input2 = DisabledInput =结果

Input3 * Input4 = DisabledInput =结果

...

用js将每一行的输入字段相乘的最佳方法是什么?

使用getElementsById进行操作是可行的,但这意味着即使每行的逻辑相同,也要创建几十个ID。

<div class="row">
<input class="input first" id="id1" type="text" name="first" oninput="calculate()" value="" placeholder="Enter number">
<input class="input second" id="id2" type="text" name="second" oninput="calculate()" value="" placeholder="Enter number">
<input class="input result" id="idResult" type="text" name="result" oninput="calculate()" value="" placeholder="Enter number">
</div>
 function calculate() {
        var first = document.getElementById('id1').value;   
        var second = document.getElementById('id2').value;
        var result = document.getElementById('idResult');   
        var finalResult = id1 * id2;
        idResult.value = Math.round(finalResult * 100) / 100;
        }

我尝试使用

var get = function(clsName) {
          return document.getElementsByClassName(clsName)[0];
        };

get('result').innerHTML = +get('first').innerHTML * +get('second').innerHTML;

但是它不起作用。我只是想知道对这样的问题最好的方法是什么?肯定不会因为做同一件事而输入50个不同的ID?

2 个答案:

答案 0 :(得分:1)

更新

新解决方案

使用.class属性
请参阅演示2。
如果[name]对于某个属性太忙,而您担心可能存在的冲突,则.class对于此特定解决方案可能同样有效。在演示2中,所有[name]属性现在都是.class属性。使用.className属性代替.name属性。如果任何目标元素具有多个类,请使用.classList.contains()属性和方法。

原始解决方案

使用[name]属性
请参阅演示1。
只要您的布局模式始终相同

<input...> <input...> <output...> 

您可以有无限数量的输入/输出组合,它们通过delegating an event彼此独立地操作。提供的演示具有一个表单标签,该表单标签可在触发输入事件时管理嵌套在其中的所有form controls。只要表单控件通过键入或选择从用户获取数据,就会发生输入事件。用于引用表单标签的简洁语法(请参见演示中的第一条评论)来自HTMLFormElement接口。另外,不要使用其他输入作为结果,而应使用输出标签,并在输入上使用type='number',这将有助于正确输入。演示中将对详细信息进行评论。

注意:我有意将表达式保留在函数之外(对我来说,这看起来过多了,因为没有提供关于该表达式的上下文或解释)。如果仍要使用它,只需将F行替换为以下内容:

let product = origin.valueAsNumber * B.valueAsNumber;
C.value = Math.round(product * 100) / 100;

对X行执行相同的操作,并将B.valueAsNumber;替换为A.valueAsNumber;

演示1

/* 
Register the first form on the page to the input event
When any input within the form gets user data call function multiply()
*/
document.forms[0].oninput = multiply;

/** multiply()
//A - Pass Event Object
//B - Find input getting the user data - e.target always points to
      the input getting data or button getting clicked, etc. 
//C - if origin's [name=factorA]...
//D - ...then B is the tag after origin...
//E - ...and C is the tag after B...
//F - ...Set the value of C as the product of A and B
      All form control values are strings not numbers, so once a
      value is extracted from a form control it must be converted
      to a number -- input.valueAsNumber is one of several ways
      to do so.
- The second control statement handles input event if origin is
[name=factorB]
*/
function multiply(e) { //A
  const origin = e.target; //B
  if (origin.name === 'factorA') { //C
    let B = origin.nextElementSibling; //D
    let C = B.nextElementSibling; //E
    C.value = origin.valueAsNumber * B.valueAsNumber; //F
  } else if (origin.name === 'factorB') {
    let A = origin.previousElementSibling;
    let C = origin.nextElementSibling;
    C.value = origin.valueAsNumber * A.valueAsNumber; //X
  } else {
    return false;
  }
}
:root {
  font: 700 3vw/1.2 Consolas
}

input,
output,
label {
  display: inline-block;
  font: inherit;
  text-align: right;
}

input {
  width: 30vw
}
<form>
  <fieldset>
    <legend>Multiplication</legend>
    <label>
    <input name='factorA' type='number' value='0'> &times; <input name='factorB' type='number' value='0'> &equals; <output name='product'>0</output>
    </label><br>
    <label>
    <input name='factorA' type='number' value='0'> &times; <input name='factorB' type='number' value='0'> &equals; <output name='product'>0</output>
    </label><br>
    <label>
    <input name='factorA' type='number' value='0'> &times; <input name='factorB' type='number' value='0'> &equals; <output name='product'>0</output>
    </label><br>
  </fieldset>
</form>

演示2

/* 
Register the first form on the page to the input event
When any input within the form gets user data call function multiply()
*/
document.forms[0].oninput = multiply;

/** multiply()
//A - Pass Event Object
//B - Find input getting the user data - e.target always points to
      the input getting data or button getting clicked, etc. 
//C - if origin's .factorA...
//D - ...then B is the tag after origin...
//E - ...and C is the tag after B...
//F - ...Set the value of C as the product of A and B
      All form control values are strings not numbers, so once a
      value is extracted from a form control it must be converted
      to a number -- input.valueAsNumber is one of several ways
      to do so.
- The second control statement handles input event if origin is
.factorB
*/
function multiply(e) { //A
  const origin = e.target; //B
  if (origin.className === 'factorA') { //C
    let B = origin.nextElementSibling; //D
    let C = B.nextElementSibling; //E
    C.value = origin.valueAsNumber * B.valueAsNumber; //F
  } else if (origin.className === 'factorB') {
    let A = origin.previousElementSibling;
    let C = origin.nextElementSibling;
    C.value = origin.valueAsNumber * A.valueAsNumber; //X
  } else {
    return false;
  }
}
:root {
  font: 700 3vw/1.2 Consolas
}

input,
output,
label {
  display: inline-block;
  font: inherit;
  text-align: right;
}

input {
  width: 30vw
}
<form>
  <fieldset>
    <legend>Multiplication</legend>
    <label>
    <input class='factorA' type='number' value='0'> &times; <input class='factorB' type='number' value='0'> &equals; <output class='product'>0</output>
    </label><br>
    <label>
    <input class='factorA' type='number' value='0'> &times; <input class='factorB' type='number' value='0'> &equals; <output class='product'>0</output>
    </label><br>
    <label>
    <input class='factorA' type='number' value='0'> &times; <input class='factorB' type='number' value='0'> &equals; <output class='product'>0</output>
    </label><br>
  </fieldset>
</form>

答案 1 :(得分:0)

使用getElementsByClassName

total = 0
for (instance of document.getElementsByClassName(clsName)) {
    total+=parseInt(instance.value)
}
console.log(total)

您的问题的示例

total = 0
i = 1
for (instance of document.getElementsByClassName(clsName)) {
    if (i%3!=0) {
        total+=parseInt(instance.value)
        i++
    } else {
        instance.value = total
        total = 0
        i = 1
    }
}

使用getElementById

ids = ['id1', 'id2', 'idResult']
for (let id of ids) {
  console.log(document.getElementById(id).value)
}
相关问题