解析类以特定文本开头并包含数字?

时间:2013-12-28 07:23:08

标签: javascript jquery css

我有一组元素:

<option class="dd dd395124 test"></option>
<option class="dd dd0295 eols"></option>
<option class="dd dd6864625 option2"></option>
<option class="dd dd939506"></option>
<option class="dd dd993999 wlwps"></option>

当我点击任何这些元素时,我想解析包含ddNUMBERS的类。

这怎么可能?

4 个答案:

答案 0 :(得分:2)

尝试

一旦你有了选项元素,那么

var option;
var clazz = option.className.match(/(^|\s)(dd\d+)($|\s)/)[2]

演示:Fiddle

答案 1 :(得分:0)

已更新这只会找到'ddNUMBERS'类。

也许这个(查看jsfiddle):

HTML:

<select>
    <option class="dd dd395124 test">1</option>
    <option class="dd dd0295 eols">2</option>
    <option class="dd dd6864625 option2">3</option>
    <option class="dd dd939506">4</option>
    <option class="dd dd993999 wlwps">5</option>
</select>

<div></div>

JavaScript的:

var opt = document.getElementsByTagName('option'),
    opts = Array.prototype.slice.call(opt),
    regex = /dd\d+/gi;

opts.forEach(function(el,i,arr) {
    arr[i].onclick = function() {
        var classes = Array.prototype.slice.call(this.classList);   
        //do something with the classes, such as:
        document.getElementsByTagName('DIV')[0].innerHTML = '';

        for(i in classes) {
            if(classes[i].search(regex) > -1) {
                /* Do something...
                   In this case, it just puts the 'ddNUMBERS' class in the DIV */
                document.getElementsByTagName('DIV')[0].innerHTML += classes[i].toString();
            }
        }
    }
});

答案 2 :(得分:0)

你可以试试这个:

$('select').on('change', function () {
    thisOption = $("option:selected", this)[0];
    var classes = thisOption.classList || thisOption.className.split(' ');
    var theClass;
    $(classes).each(function (i) {
        var t = classes[i];
        console.log(t.split('dd').length);
        if (t.split('dd').length > 1 && t.length > 1) {
            theClass = classes[i];
        }
    })
    alert(theClass);
});

Demo

答案 3 :(得分:0)

尝试这样的事情

$(document).ready(function () {
    $('select').change(function (e) {
        var option = this.options[this.selectedIndex];
        var klazz = option.className.match(/dd([0-9]*)\S/)[0];
        alert(klazz);
    });
});