Didiblu Didiblu - 5 months ago 17
jQuery Question

How to get a value inside a clickHandler function jQuery

I'm trying to make my website work on all mobile devices, including iOS.
I order to do it I had to use a clickHandler function as suggested here How to replace click with touchstart on iOS devices

I need to get a value but using $this I receive the error "is not defined".

<button class="open" value="{{ item.id }}">open</button>


var clickHandler = ('ontouchstart' in document.documentElement ? "touchstart" : "click");

$(".open").bind(clickHandler, function(e) {
var id = ($this.attr('value'));
$("#item" + id).addClass("visible");
});


Any suggestion? Thanks!

Answer

Remember, this is a reference to the member that invokes the current function, in your case the DOM element (button). $() is the jQuery constructor function. Wrapping this in $() means you are turning DOM element into jQuery object. So what you need is either:

this.getAttribute("value")

or

$(this).attr("value")

.

$this has no meaning in your context, that's why you are getting undefined.