jeudi 26 mars 2015

How can I find the element clicked on inside a jquery handler?


I'm trying to do a specific action on the clicked element if an argument is passed in the on click method in jquery. When I try to access "this" it's referencing the entire window instead of the clicked on element. How would I access the clicked on element in the handler?


Here's the code I'm using:



var myfunction = function(action) {
var content;
var $this = $(this);
if(action === "one") {
$(".output").text("clicked on one");
$this.addClass("one");
}
if(action === "two") {
$(".output").text("clicked on two");
$this.addClass("two");
}
};
$("#button").on("click", function(event) {
myfunction("one");
});

$("#button2").on("click", function(event) {
myfunction("two");
});


I set up an example on jsbin here. Any help would be appreciated.





Aucun commentaire:

Enregistrer un commentaire