Shniper Shniper - 7 months ago 13
Javascript Question

How to determine if $(this) is in array on click event

I have a set of

id
values in 4 arrays. Each array will be assigned a text value for an h1 and a p that I haven't put in yet. Right now I'm just trying to get it to alert if one of the images in array graphicDesign is clicked. I tried using $.inArray

DEMO

var graphicDesign = [$('#design'), $('#DD'), $('#SElogo')];
var webDesign = [$('#bootstrap'), $('#farm'), $('#pong'), $('#SE'), $('#dung')];
var programming = [$('#SE'), $('#dung'), $('#sacar')];
var other = [$('#firm')];

function categories() {
if ($.inArray(this, graphicDesign) > -1) {
alert('hello');
}
}

Answer

You should not store DOM objects in an array and try to match them with $.inArray. Using ids or another attribute would be a better solution.

For example :

https://jsfiddle.net/1f9xd3t0/

var graphicDesign = ['design', 'DD', 'SElogo'];

function categories(id) {
  if ($.inArray(id, graphicDesign) > -1) {
    alert('hello');
  }
}  

categories('design');
Comments