Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "this" reference of the element calling the function?

For example I want a function that is used by many elements to get the attributes of the calling element.

function example(){
    var name = //name of the calling element "$(this).attr('name')"
}
<button name="somename1" onclick="example()">Button1</button>
<button name="somename2" onclick="example()">Button2</button>

so if the button named 'somename1' calls the function, the variable 'name' will be assigned to 'somename1' and so if 'somename2' called it, it will be assigned to 'somename2'

like image 297
Khaled Avatar asked Sep 17 '12 09:09

Khaled


People also ask

How do you call a function in a function?

To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.

How do you reference a function in JavaScript?

In Pass by Reference, a function is called by directly passing the reference/address of the variable as the argument. Changing the argument inside the function affects the variable passed from outside the function. In Javascript objects and arrays are passed by reference.

How do you call a function in HTML?

To invoke this function in the html document, we have to create a simple button and using the onclick event attribute (which is an event handler) along with it, we can call the function by clicking on the button.

What does this refer to in a function?

“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.


1 Answers

Use This:

function exampleFunction(exampleElement) {
    var name = exampleElement.name;
}

<button name="somename1" onclick="exampleFunction(this)">Button1</button>
<button name="somename2" onclick="exampleFunction(this)">Button2</button>

But if you use jquery, you could do

$('button').click(function() {
  var name = $(this).attr('name');
});

Without the onclick attribute.

like image 127
xdazz Avatar answered Nov 15 '22 14:11

xdazz