使用属性class元素作为数组

时间:2011-11-30 14:19:22

标签: javascript jquery

我注意到一些验证工具使用“class”属性将选项传递给验证脚本。

示例:

<input class="input-field validate[required, email]" name="" type="text" />

“必需”和“电子邮件”将被脚本选为设置选项。

我想知道是否有一种简单的方法可以实现这一点,或者这可能已经在jQuery中提供了? 我想用它作为将某些设置传递给我的脚本的方法。

任何帮助将不胜感激, 感谢

修改

谢谢@loseb你的例子很棒。 我试图通过对您的示例进行一些小修改来实现另一件事:

function classAttributes( classString, className ) {
    var data;
    var regex = new RegExp(className+"\[(.*?)\]");
    var matches = classString.match(regex);

    if ( matches ) {
        //matches[1] refers to options inside [] "required, email, ..."
            var spec = matches[1].split(/,\s*/);

            if ( spec.length > 0 ) {
                data = spec;
            }
    }

    return data;
}

任何想法为什么“new RegExp(className +”[(。*?)]“);”不起作用。 var匹配为空。

修改 问题的第二部分移至: javascript regex pattern with a variable string not working

1 个答案:

答案 0 :(得分:2)

如果我理解正确,这就是解决方案:

var className = $('.input-field').att('class');
var regex = /validate\[(.*?)\]/;
var matches = className.match(regex);

if (matches) {
    //matches[1] refers to "required, email" string
    var spec = matches[1].split(/,\s*/);

    if (spec.length == 2) {
        var attribute = spec[0]; //required or optional or anything else
        var validator = spec[1]; //actual validation type
    }
}