Domanda

I have an array with buttons:

var buttonnumber = ["#btn1", "#btn2", "#btn3", "#btn4", "#btn5"];

If one of them is clicked I want to get their index-value in the array:

$("#btn1, #btn2, #btn3, #btn4, #btn5").click(function() {
var y = buttonnumber.indexOf(this); //($(this)) doesn't work either!
});

This doesn't work. I used the jQuery method .index() instead:

var y = $(this).index();

but I'd rather not because the order of the buttons in the html is not the same as in the array.

Thanks for your help!

È stato utile?

Soluzione

Since your array has IDs with hashes, then you need to search for the ID with a hash, not the element itself. There are two solutions:

Make your button array reference objects instead of IDs

var buttonnumber = [$("#btn1"), $("#btn2"), $("#btn3"), $("#btn4"), $("#btn5")];

$("#btn1, #btn2, #btn3, #btn4, #btn5").click(function() {
    var y = buttonnumber.indexOf($(this));
});

or do the indexOf against the id of the object you are clicking:

var buttonnumber = ["#btn1", "#btn2", "#btn3", "#btn4", "#btn5"];

$("#btn1, #btn2, #btn3, #btn4, #btn5").click(function() {
    var y = buttonnumber.indexOf("#" + this.id);
});

You can also write that click selector as:

var buttonnumber = ["#btn1", "#btn2", "#btn3", "#btn4", "#btn5"];

$(buttonnumber.join()).click(function() {
    var y = buttonnumber.indexOf("#" + this.id);
});

In modern browsers, you also no longer need jQuery for something like this:

var buttonnumber = ["#btn1", "#btn2", "#btn3", "#btn4", "#btn5"];
// cast nodelist that's returned from querySelectorAll to array
Array.prototype.slice.call(document.querySelectorAll(buttonNumber.join()))
    .forEach(el => {
        el.addEventListener("click", (event) => {
            let y = buttonnumber.indexOf("#" + this.id);
        });
    })

Altri suggerimenti

buttonnumber.indexOf(this);

Supposed to be

buttonnumber.indexOf('#' + this.id);

this corresponds to the DOM element. Need to get the id of that element and get the index based of of it.

Get the clicked items ID attribute with $(this).attr('id') and get your index from the string...

$("#btn1, #btn2, #btn3, #btn4, #btn5").click(function() {
    var y = buttonnumber.indexOf($(this).prop("id"));
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top