JQuery从多个类值获得最后一个

时间:2022-05-29 01:31:35

I have a couple of div's that look like this:

我有一些像这样的div:

<div class="film cars-0317219"></div>
<div class="film wall-e-0910970"></div>
<div class="film finding-nemo-0266543"></div>
<div class="film cars-0317219"></div>

Im concerned with the second (so last) class name, but only of the divs that have the class 'film'. Is there any way I can get the last class name with JQuery?

我只关心第二个(也是最后一个)类名,但只关心有类“film”的女歌手。有没有办法用JQuery得到最后的类名?

To give you an example of what I want to do look below. I want to make these div's clickable and let the visitor go to /title/last-class-name.html

为了给你一个我想做的事情的例子,请看下面。我想让这些div成为可点击的,让访问者进入/title/last-class name.html

$('div.film').live('click', function(){

    // This returns the whole 'film random-title-id'
    // instead of just 'random-title-id'
    var id = $(this).attr('class');

    location.href = '/title/' + id + '.html';

});

1 个解决方案

#1


7  

This should work:

这应该工作:

$('div.film').live('click', function(){

    var classes=$(this).attr("class").split(" ");
    var id=classes[classes.length-1];

    location.href = '/title/' + id + '.html';

});

although if you don't already have IDs on your elements, this seems like it would make more sense as an ID.

尽管如果您的元素上没有ID,这看起来更适合作为ID。

#1


7  

This should work:

这应该工作:

$('div.film').live('click', function(){

    var classes=$(this).attr("class").split(" ");
    var id=classes[classes.length-1];

    location.href = '/title/' + id + '.html';

});

although if you don't already have IDs on your elements, this seems like it would make more sense as an ID.

尽管如果您的元素上没有ID,这看起来更适合作为ID。