【问题标题】:javascript passing the class index on a function calljavascript 在函数调用中传递类索引
【发布时间】:2018-08-13 14:34:09
【问题描述】:

大家好,我需要知道如何在调用函数时将类索引传递给函数。

假设我有 3 个像这样的输入标签:

<input type="text" placeholder="email" class="PIC" 
onchange="val(this.getAttribute('class'), **index0**)" />
<input type="text" placeholder="email" class="PIC" 
onchange="val(this.getAttribute('class'), **index1**)" />
<input type="text" placeholder="email" class="PIC" 
onchange="val(this.getAttribute('class'), **index2**)" />

现在我想做的就像我传入类名一样,我想传入调用函数的类索引。 index0 应该传入 0 index1 1 应该传入 1 等等...

假设函数 val 是这样的:

function val(className, Index) {
  alert('class is ' + className + ' and the index is: ' + index);
}

【问题讨论】:

  • 类索引是什么意思?

标签: javascript function class arguments


【解决方案1】:

你可以这样做:

    document.querySelectorAll(".PIC").forEach(function(input, index){
        input.onchange = val(input.getAttribute('class'), index);
    })  

【讨论】:

    【解决方案2】:

    您想在 JavaScript 中添加一个事件侦听器。我将其保留为change 事件,尽管您可能会发现input 事件更合适。

    我还添加了一个 val 函数来记录信息,因为没有提供。

    document.querySelectorAll('.PIC').forEach(function(ele, index) {
          ele.addEventListener("change", function(e) {
            let myClass = ele.getAttribute('class')
            val(myClass, index);
          });
        });
    
    function val(eleClass, eleIndex) {
    console.log(eleClass, eleIndex);
    }
    <input type="text" placeholder="email" class="PIC" />
    <input type="text" placeholder="email" class="PIC" />
    <input type="text" placeholder="email" class="PIC" />

    【讨论】:

    • @BenGababy 我知道吗?有什么问题?
    • 仅供学习之用。有没有办法像我一样通过类 indez 来保持它,就像我传入类名一样。我只是在学习 javascript 我仍然不懂复杂的代码。非常感谢您的回答
    • @BenGababy 不,没有办法在标记中隐式传递索引。您要么需要在调用函数的每个元素的调用中显式声明它,预先通过代码添加事件侦听器,要么在函数运行时弄清楚它。
    猜你喜欢
    • 1970-01-01
    • 2011-08-29
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    相关资源
    最近更新 更多