html对象可以将自身作为参数传递给JS函数吗

时间:2019-04-03 08:11:57

标签: html arguments

假设我有一个看起来像这样的HTML代码:

<div class="button" onclick="clickMe()">1</div>
<div class="button" onclick="clickMe()">2</div>
<div class="button" onclick="clickMe()">3</div>
<div class="button" onclick="clickMe()">4</div>

我希望我的clickMe函数输出如下内容: You clicked the button No. 3

换句话说,我需要每个按钮将“自身”作为参数传递给该函数……这可能吗? 像<div class="button" onclick="clickMe(self)">2</div>

2 个答案:

答案 0 :(得分:1)

您可以将this关键字传递给clickMe方法,该方法将引用单击的元素。然后,您可以使用.textContent从单击的div

中检索号码。

function clickMe(elem) {
  console.log("You have clicked " +elem.textContent);
}
<div class="button" onclick="clickMe(this)">1</div>
<div class="button" onclick="clickMe(this)">2</div>
<div class="button" onclick="clickMe(this)">3</div>
<div class="button" onclick="clickMe(this)">4</div>

或者,您可以改为使用click事件侦听器,这将防止您在每个元素上重复相同的函数调用:

document.querySelectorAll('.button').forEach(elem => {
  elem.addEventListener('click', function() {
    console.log("You have clicked " +this.textContent);
  });  
});
<div class="button">1</div>
<div class="button">2</div>
<div class="button">3</div>
<div class="button">4</div>

答案 1 :(得分:0)

您可以使用id元素,然后可以传递this.id

function clickMe(val) 
  { alert("You clicked the button No. "+val); }
<div class="button" id = "1" onclick="clickMe(this.id)">1</div>
<div class="button" id = "2" onclick="clickMe(this.id)">2</div>
<div class="button" id = "3" onclick="clickMe(this.id)">3</div>
<div class="button" id = "4" onclick="clickMe(this.id)">4</div>