Get element from which onclick function is called

前端 未结 8 877
野趣味
野趣味 2021-01-18 03:59

I have a button with a onclick attribute which is pointing to the function test().


<         


        
相关标签:
8条回答
  • 2021-01-18 04:51

    I came across an other extremely simple way to do it in Vanilla JS so I post it here for reference:

    function whoami () {
      var caller = event.target;
      alert("I'm " + caller.textContent);
    }
    <button onclick="whoami()">Button 1</button>
    <button onclick="whoami()">Button 2</button>
    <button onclick="whoami()">Button 3</button>

    I'm not sure about the browser support for it but it works at least on Safari, Firefox and Blink based browsers.

    0 讨论(0)
  • 2021-01-18 04:55

    	function test(button)
    	{
    	    var button_name = button.getAttribute('name');
    	    console.log("Im button "+ button_name);
    	}
    	<button onclick="test(this)" name="button1">Button 1</button>
    	<button onclick="test(this)" name="button2">Button 2</button>
    	<button onclick="test(this)" name="button3">Button 3</button>

    0 讨论(0)
提交回复
热议问题