我有 6 个类的 div。我想知道该 div 是否具有一类、二类、三类或四类,并将其设置为选择框的值。我只想搜索这4个类,不关心div中的其他类。我有以下内容。有没有更好的写法。
<div class="four whatever something"></div>
<select>
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
</select>
if ($('div').hasClass(one)) {
$('select').val('one')
} else if ($('div').hasClass('two')) {
$('select').val('two')
}
if ($('div').hasClass('three')) {
$('select').val('three')
}
if ($('div').hasClass('four')) {
$('select').val('four')
}
最佳答案
你可以尝试这样的事情:
var classes = $('div').attr('class').split(/\s/);
for ( var i in classes )
$('select').val(classes[i]);
关于javascript - jQuery 从指定类列表中搜索类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7987117/