【问题标题】:Javascript: indexOf($(this) to get the array-index value of clicked element?Javascript: indexOf($(this) 获取点击元素的数组索引值?
【发布时间】:2013-12-14 00:04:03
【问题描述】:

我有一个带有按钮的数组:

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

如果其中一个被点击,我想在数组中获取它们的索引值:

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

这不起作用。 我使用了 jQuery 方法 .index() 代替:

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

但我宁愿不这样做,因为 html 中按钮的顺序与数组中的不同。

感谢您的帮助!

【问题讨论】:

  • this 是 DOM 元素,而不是它的 ID。

标签: javascript jquery arrays this indexof


【解决方案1】:

由于您的数组具有带有哈希的 ID,因此您需要搜索带有哈希的 ID,而不是元素本身。有两种解决方案:

让您的按钮数组引用对象而不是 ID

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

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

或者对你点击的对象的 id 执行 indexOf:

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

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

你也可以把点击选择器写成:

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

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

在现代浏览器中,您也不再需要 jQuery 来处理类似这样的事情:

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);
        });
    })

【讨论】:

    【解决方案2】:
    buttonnumber.indexOf(this);
    

    应该是

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

    this 对应于DOM 元素。需要获取该元素的 id 并基于它获取索引。

    【讨论】:

      【解决方案3】:

      使用$(this).attr('id') 获取点击项 ID 属性并从字符串中获取您的索引...

      【讨论】:

        【解决方案4】:
        $("#btn1, #btn2, #btn3, #btn4, #btn5").click(function() {
            var y = buttonnumber.indexOf($(this).prop("id"));
        });
        

        【讨论】:

          猜你喜欢
          • 2017-02-08
          • 2012-02-06
          • 1970-01-01
          • 1970-01-01
          • 2023-03-18
          • 1970-01-01
          • 2023-03-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多