简体   繁体   English

如何使用onclick事件处理程序识别元素

[英]How to identify an element using an onclick event handler

I want to send the ID of an element to the function to know what button pressed it. 我想将元素的ID发送给函数,以了解按下了什么按钮。

<input type="submit" id="foo" onclick="function(abcxyz)" value="abc" />
<input type="submit" id="foo" onclick="function(xyz)" value="x" />

function(str){
    if(str == abcxyz){
        //do this.
    }
    else if(str == xyz){
        //do that.
    }
}

or if it's possible, its okay that the value abc or x will be send to the function. 或者如果可能的话,可以将值abc或x发送到该函数。 so str = abc or str = x. 所以str = abcstr = x。

If I have understood your problem correctly... 如果我正确理解了您的问题...

  1. You are missing a function name 您缺少函数名称
  2. The two inputs have the same id 两个输入具有相同的ID
  3. using submit for type doesn't make sense in your case 在您的情况下,使用Submit作为类型没有意义
  4. The values of the inputs aren't needed for this task 此任务不需要输入的值

     <input type="button" id="foo1" onclick="button_click('1')" /> <input type="button" id="foo2" onclick="button_click('2')" />` function button_click(str){ if(str == '1'){ alert('Button with id foo1 was pressed'); } else if(str == '2'){ alert('Button with id foo2 was pressed'); } } 

You can use the answer that you'll find here . 您可以使用在这里找到答案

Basically write 基本上写

<input type="submit" onclick="yourFunction(this.id)" id="abc" value="Button abc" />

Your function needs a name: 您的函数需要一个名称:

Try: 尝试:

<script type="text/javascript">
    function whichButton(str){
        if(str == 'abc'){
            alert('abc was clicked');
        }
        else if(str == 'x'){
            alert('str was clicked');
        }
    }
</script>
<input type="submit" id="foo" onclick="whichButton(this.value);" value="abc" />
<input type="submit" id="foo1" onclick="whichButton(this.value);" value="x" />

As a solution to your problem please refer the code snippet mentioned below 为了解决您的问题,请参考下面提到的代码段

Eg 例如

  <input type="submit" id="foo" onclick="function(this.value)" value="abc" />
  <input type="submit" id="foo" onclick="function(this.value)" value="x" />

In above code snippet this object will refer to event source ie submit button 在上面的代码片段中,该对象将引用事件源,即提交按钮

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM