当使用 javascript 单击时,有没有办法在 DOM 中的许多按钮列表中识别一个按钮的索引?
Is there a way to identify the index of one button among a list of many buttons in the DOM when it is clicked using javascript?
我需要提醒点击按钮索引的功能
var openformbtn=document.querySelectorAll('.show-form');
var formcontainer=document.querySelectorAll('.form-container');
var btnarray = Array.from(openform);
openformbtn.addEventListener('click', displayform);
function displayform(e){
this.nextElementSibling.style.display='flex';
var i = btnarray.index(this);
i.style.display='flex';
}
有不同的方法,
id
在 HTML
给每个按钮一个唯一的id
,当按钮被点击时,从事件对象e
中获取id
。
id
传入JS
为按钮添加事件监听器时,将监听器包装在匿名函数中并将 id
作为参数传递,例如
openformbtn.addEventListener('click', function(){
displayform(id)
});
当你点击的时候,它传递一个点击事件给函数,比如:
// We are selecting all the buttons
const btns = document.querySelectorAll("button");
// we are looping throught the selected buttons.
btns.forEach(btn => {
// we are adding a click event to the buttons.
// the (e) stands for event
btn.addEventListener("click", (e) => {
// e stands for event
// To get the clicked element you use e.target
// document.querySelectorAll returns a NodeList
// To use indexOf we need to make it an array.
// That is what Array.from() is for.
const index = Array.from(btns).indexOf(e.target);
// Now we call a alert using the index
alert(index);
});
});
<button>0</button>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
我需要提醒点击按钮索引的功能
var openformbtn=document.querySelectorAll('.show-form');
var formcontainer=document.querySelectorAll('.form-container');
var btnarray = Array.from(openform);
openformbtn.addEventListener('click', displayform);
function displayform(e){
this.nextElementSibling.style.display='flex';
var i = btnarray.index(this);
i.style.display='flex';
}
有不同的方法,
id
在 HTML
给每个按钮一个唯一的id
,当按钮被点击时,从事件对象e
中获取id
。
id
传入JS
为按钮添加事件监听器时,将监听器包装在匿名函数中并将 id
作为参数传递,例如
openformbtn.addEventListener('click', function(){
displayform(id)
});
当你点击的时候,它传递一个点击事件给函数,比如:
// We are selecting all the buttons
const btns = document.querySelectorAll("button");
// we are looping throught the selected buttons.
btns.forEach(btn => {
// we are adding a click event to the buttons.
// the (e) stands for event
btn.addEventListener("click", (e) => {
// e stands for event
// To get the clicked element you use e.target
// document.querySelectorAll returns a NodeList
// To use indexOf we need to make it an array.
// That is what Array.from() is for.
const index = Array.from(btns).indexOf(e.target);
// Now we call a alert using the index
alert(index);
});
});
<button>0</button>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>