How to find a div with part of a class name and ge

2019-03-30 09:20发布

问题:

There are several divs on my page with classes my_widget-2, my_widget-8, etc. What JavaScript or jQuery code can I use to get the number "2" (ie. the number that appends the first matching widget)?

Note: If I were to write this question again, I would change the order of these class names and ask for a way to get "8" in order to avoid giving the impression that I want the smaller number.

回答1:

$( "[class*='my_widget']" ).each ( function () {
    var elClasses = $( this ).attr ( 'class' ).split ( ' ' );

    for ( var index in elClasses ) {
        if ( elClasses[index].match ( /^my_widget-\d+$/ ) ) {
            var classNum = elClasses[index].split ( '-' )[1];
            alert ( classNum );
            break;
        }
    }
} );

Use the "attributeContains" selector to get all elements that have a class my_widget-*, and then loop trough all the classes the element has searching for you class. Once you find it, extract the number part.



回答2:

This should do the trick:

$("[class^='my_widget']").each(function() {
    var classParts = $(this).attr('class').split('-');
    var number = classParts.pop();
});

Please note that it will only work if there is a singular class, otherwise you'd get something like 8 otherclass as a result.



回答3:

Basic JS approach:

<div id="x" class="widget-2 lang-日本語">foo</div>

function Element_getClassArgument(el, name) {
    var classes= el.className.split(' ');
    var prefix= name+'-';
    for (var i= classes.length; i-->0;)
        if (classes[i].substring(0, prefix.length)==prefix)
            return classes[i].substring(prefix.length);
    return null;
}

Element_getClassArgument(document.getElementById('x'), 'widget'); // 2

If you wanted to include whitespace characters, or a hyphen in a name, you'd have to introduce an encoding scheme of some sort, for example encodeURIComponent. But often you can get away without that.

Wrapping in something with $ in the name is left as an exercise for the reader. :-)



回答4:

If you want to get the DIV elements with a class my_widget-2, use this selector:

$("div.my_widget-2")

But if you want to get all DIV elements with a class of the form my_widget-N where N is an arbitrary number, try this:

$("div[class]").each(function() {
    var matches = this.className.match(/(?:^|\s+)my_widget-(\d+)(?:\s+|$)/g);
    if (matches !== null) {
        alert(matches);
    }
})


回答5:

Try element.attr('class').match(/my_widget-(\d+)/)[1]

It should return the column number as a string so just run parseInt() on it