开发者

How to get a number from a dynamic class name from a list of classes using jquery

My situation is this: I have an HTML list element with an unknown amount of classes (has to be dynamic) and I am adding two classes to this list of classes. Upon clicking a link buried within the , I need to be able to dynamically grab a number from one of the classes I add to it.

My classes I add to the list are 'display-container' and 'display-#' (# representing the number I need).

Below is my current solution but, there has to b开发者_如何转开发e a better way to get this number. Any help would be greatly appreciated.

$.each($(this).closest('.display-container').attr('class').split(' '), function(i, item) { if(this.match('^display-[0-9]+')) { currentObj = item.split('-')[1]; } } )

The code I am working on will be going into a plugin (which is why I need the dynamic class list). An example list element is given below.

                    <loop query="itemList">
                    <li class="item-#currentRow#">
                        <table>
                            <tr>
                                <td class="vat">
                CONTENT
                                </td>
                                <td class="vat">
                CONTENT
                                </td>
                                <td class="vat">
                CONTENT
                                </td>
                                <td class="vat">
                                    <span><a href="javascript://" class="edit" id="edit-#id#">Edit</a></span>
                                    <span><a href="javascript://" class="delete" id="delete-#ID#">Delete</a></span>
                                </td>
                            </tr>
                        </table>
                    </li>
                    </loop>
                </ul>`


my understanding of your html setup

canned my html, using yours.

Javascript:

var regEx = /display-[\d]+/;
var classesLongString = $(this).closest('li').attr('class');
var yourDisplayNumberClass = regEx.exec(classesLongString );
var currentObj = 0;
if(yourDisplayNumberClass){
   currentObj = yourDisplayNumberClass.split('-')[1];
}

you now have display-## in the above variable.


Maybe:

$('.display-container a').live('click',function(){
    var $cont = $(this).parents('.display-container');
    var rgx = new RegExp( "display\-(\d+)" );
    var cls   = rgx.exec( $cont.attr('class') );
    $cont.toggleClass( cls[0] , cls[0].replace( cls[1],cls[1]+1 ) );
});

[not tested]


This works:

var currentObj = /display-([0-9]+)/.exec(
                     $(this).closest('.display-container').attr('class')
                 )[1];


var regEx = /display-[\d]+/;
var currentObj = regEx.exec($(this).closest('.display-container').attr('class'))[0].split('-')[1];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜