指出JS中正在使用的DOM类的当前编号?

问题描述 投票:0回答:1

我遇到了一个问题,我需要指出我在JS中使用的类的当前编号。例如我的代码是这样的。

<div>
<p class="child"><button type="submit" onclick="myfunction()">Click here</button></p>
<p class="child"><button type="submit" onclick="myfunction()">Click here</button></p>
<p class="child"><button type="submit" onclick="myfunction()">Click here</button></p>
<p class="child"><button type="submit" onclick="myfunction()">Click here</button></p>
</div>

现在我知道如果我输入 document.getElementsByClassName("child")它将为我提供一个数组,其中包含了p类的所有用法。但是我想知道具体是哪个按钮被点击了。

例如,如果第二个按钮p类被点击,我想让我的函数返回数字2。同样的,如果第三个按钮被点击,我希望返回数字3。有什么函数可以实现吗?我应该如何操作?我是一个完全陌生的JS。

javascript html dom
1个回答
1
投票

你要做的是调用 活动委托 在javascript中,你只需在父元素上添加事件监听器。你只需在父元素上添加事件监听器,以避免为多个子元素添加事件处理程序。

e.target 父元素的事件监听器提供了事件处理程序(这里是click)被调用的元素。你可以使用不同的属性来获取该元素的信息,如 e.target.textContent 给你按钮文本。

const container = document.querySelector(".container")

container.addEventListener('click',(e)=>{
  console.log(e.target)
  console.log(e.target.textContent)
})
<div class="container">
  <p><button type="button">Click here 1</button></p>
  <p><button type="button">Click here 2</button></p>
  <p><button type="button">Click here 3</button></p>
  <p><button type="button">Click here 4</button></p>
</div>

0
投票

你可以通过 this 的函数,也就是当前元素。我已经添加了代码来查找所有的 .child 元素,并找到与这个按钮的父节点相匹配的索引,然后提醒它。我建议使用 addEventListener 而不是onclick属性。根据你正在做的事情,我建议你添加 data="n" 属性添加到DOM元素中,或者是一个值的对象映射。 但是这个可以照样工作。

function myfunction(el){
   const index = Array.from(document.getElementsByClassName('child'))
                      .findIndex(x=>x===el.parentNode);
   alert(index);
}
<div>
<p class="child"><button type="submit" onclick="myfunction(this)">Click here</button></p>
<p class="child"><button type="submit" onclick="myfunction(this)">Click here</button></p>
<p class="child"><button type="submit" onclick="myfunction(this)">Click here</button></p>
<p class="child"><button type="submit" onclick="myfunction(this)">Click here</button></p>
</div>

0
投票

你可以循环浏览拥有这个类的元素列表, 在每个元素上添加事件监听器, 这样你就可以正常访问函数中的数字. 下面是一个例子。

let childs = document.getElementsByClassName('child');
for(let i = 0; i < childs.length; i++){
      let el = childs[i];
      el.addEventListener('click', function(e){
            console.log(i+1);
      });
}
<div>
     <p class="child"><button type="submit">Click here 1</button></p>
     <p class="child"><button type="submit">Click here 2</button></p>
     <p class="child"><button type="submit">Click here 3</button></p>
     <p class="child"><button type="submit">Click here 4</button></p>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.