使用“Starts With”选择器获取类名值

时间:2015-04-09 08:55:42

标签: jquery html

对于HTML等

<a href="#" class="a b nl-3522">First</a>
<a href="#" class="a b nl-7352">Second</a>
<a href="#" class="a b nl-4874">Third</a>
<!-- Note that classes nl-* are being added dynamically and are random so I can't 
   hardcode the value -->
<!-- Also, the number of classes can vary for each anchor -->

我试图获取以nl-开头的类的值。以下是我目前拥有的事件处理程序

$('.a').on('click', function(e){
        e.preventDefault();
        var $anchor = $(this);
        // how do I use class^="nl-" here so that I get the value nl-3522
        // if I click on "First" or nl-7352 if I click on "Second"...
});

添加小提琴,使作业更容易实时测试: JSFIDDLE

5 个答案:

答案 0 :(得分:1)

这是通过拆分类然后匹配来实现的,因此完全独立于类的索引:

$('.a').on('click', function(e){
            e.preventDefault();
            var $anchor = $(this);            

            var get = $.grep(this.className.split(" "), function(v, i){
               return v.indexOf('nl-') === 0;
           }).join();

            alert(get);
            // how do I use class^="nl-" here so that I get the value nl-3522
            // if I click on "First" or nl-7352 if I click on "Second"...
});

https://jsfiddle.net/snxhgLf5/7/

答案 1 :(得分:0)

尝试

$('.a').on('click', function(e){
            e.preventDefault();
            var $anchor = $(this).attr('class').split(" ")[2];            
           alert($anchor)
});

Fiddle

答案 2 :(得分:0)

您可以使用下面的contains selector *

$('.a[class*="nl-"]').on('click', function(e){
            e.preventDefault();
            var $anchor = $(this);
            // how do I use class^="nl-" here so that I get the value nl-3522
            // if I click on "First" or nl-7352 if I click on "Second"...
});

<强> JSFiddle Demo

答案 3 :(得分:0)

试试这个

$('.a').on('click', function(e){
        e.preventDefault();
        var $anchor = $(this);
        if(($anchor.attr("class")).indexOf("nl-")>=0)
           alert($anchor.attr("class"));
});

Fiddle Demo

答案 4 :(得分:0)

你可以试试这个:

$(":contains('nl-')").on('click', function(e){...