【问题标题】:Finding Dom Node Index for elements of a certain class of a multi-class element查找多类元素的某个类的元素的Dom节点索引
【发布时间】:2014-04-12 12:30:59
【问题描述】:

您好,我有一系列包含多个不同类别的标签。单击跨度时,我想返回跨度类的索引。所以不是跨度本身的索引。

这是一个示例 html:

<span class='spantype1 party'>text1</span>
<span class='spantype2 party'>text2</span>
<span class='spantype1 party'>text3</span>

所以如果我点击 text3 我想返回 1 而不是 2。如果我点击 text1 我想返回 0。当然如果我点击 text2 我想返回 0。

来自here 的这个答案不起作用,因为索引总是返回为-1(因为有多个类),请参阅my example jsfiddle

$( "span" ).click(function() {
    var index = $('.' + $(this).attr('class')).index($(this));
    alert(index);
});

【问题讨论】:

    标签: javascript jquery dom indexing


    【解决方案1】:

    我会使用过滤器来抓取您感兴趣的课程,然后根据它进行搜索:

    $("span").click(function() {
        var spanType = $.grep(this.classList, function (className) {
            return /^spantype/.test(className);
        })[0];
    
        var index = $('.' + spanType).index($(this));
        alert(index);
    });
    

    我在上面使用了classList,但为了获得更好的支持(请参阅caniuse.com),您可能可以改用className

    $("span").click(function() {
        var spanType = $.grep(this.className.split(/\s+/), function (className) {
            return /^spantype/.test(className);
        })[0];
    
        var index = $('.' + spanType).index($(this));
        alert(index);
    });
    

    【讨论】:

      猜你喜欢
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      • 2017-04-07
      相关资源
      最近更新 更多