从类名获取产品ID,例如'productID_123'

Joh*_*lia 1 javascript jquery

我已经在产品图片列表中添加了一个类,例如'productID_123',我想从最后得到这个数字.我需要这个尽可能动态的图像可能有多个类.这是我到目前为止所放在一起的,我想我几乎就是无法弄清楚IF:

$(".image").each(function(){

    var classList = $(this).attr('class').split(/\s+/);

    $.each( classList, function(index, item){
        if (item === 'productID_') {
            product_id = item.replace("productID_","");
            fetchProductImages(product_id,this.width,this.height);
        }
    });

});
Run Code Online (Sandbox Code Playgroud)

也许我可以强制它是一个返回的整数?

我不能使用data-*属性,因为页面是用XHTML Strict编写的,需要验证.

Poi*_*nty 5

您可以使用正则表达式:

$.each( classList, function(index, item){
    var matched = item.match( /^productID_(\d+)$/ );
    if (matched) {
        var product_id = matched[1];
        fetchProductImages(product_id,this.width,this.height);
    }
});
Run Code Online (Sandbox Code Playgroud)