3

我想编写 javascript 代码来识别哪个按钮已被单击并更改其标签。网页上有多个按钮,因此不可能通过其 id 来引用它。它仅通过它被点击的事实来识别。我看到一个关于堆栈溢出的讨论建议写作

<input type = "button" value = " " id ="3" onclick="click(event)">

在网页上,然后将click定义为一个带有一个参数的函数,我们称之为ev。然后我通过(在函数内部)引用它

var button = ev.target;

然后尝试更改按钮的值。它没有用。我只想在单击按钮时更改按钮的标签,而无需通过 id 引用它(我不知道它的 id 是什么,因为它只是在许多人中单击的按钮)。谁能解释如何做到这一点?

4

3 回答 3

5
onclick="clickMe(this)">

This will pass a reference to the element clicked on, then you can get/set anything that you normally can from the element e.g:

function clickMe(el) {
  el.value = "Hi"; // set
  alert(el.value); // get
}

Demo

Note: calling a function click() is not allowed as it is a reserved keyword (just like you wouldn't have a function called function(), which is why I made it clickMe()

于 2013-07-04T15:53:12.160 回答
1

Pass the this keyword as a parameter, and use a data attribute to hold the new value :

html :

<input type="button" value=" " id="a3" data-value="test" onclick="func(this)">

js

function func(elem) {
    elem.value = elem.getAttribute('data-value');
}

FIDDLE

于 2013-07-04T15:52:52.017 回答
0

this设置为浏览器点击的按钮:

<input type=button onclick=clickhandler>
<script>
function clickhandler() {
    this.value = "foo";    // button’s label is now foo
    console.log(this.id);  // will print the button’s id
}
</script>
于 2013-07-04T15:58:18.620 回答