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



对于这样的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"...
});

添加fiddle也可以使作业更容易地进行实时测试:JSFIDDLE

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

$('.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/

尝试

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

Fiddle

您可以像下面的一样使用包含选择器*

$('.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演示

试试这个

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

Fiddle演示

你可以试试这个:

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

最新更新