JQuery将类添加到li元素

时间:2013-01-30 10:47:10

标签: jquery html-lists

以下是我的代码

function getName(selectName, selectedValue) {
    var partices = $('#dk_container_'+selectName);
    var selectlbl = partices.find('.dk_label');
    var ul = partices.find('.dk_options_inner');

    $('li').each(function () {
        if ($('a', this).text() == selectedValue) {
            $(this).addClass('dk_option_current');
            selectlbl.html(selectedValue);
        }
        else {
            $(this).attr('class', '');
        }
    });
}

问题是$(this).addClass('dk_option_current');。此特定行旨在在dk_option_current元素中插入类li,其中if条件满足。此selectlbl.html(selectedValue);行正常运行。但是我要添加的课程根本没有添加。请指出是否有任何问题。

HTML

 <a class="dk_toggle" style="width: 300px;">
    <span class="dk_label"></span>
    </a>
    <div class="dk_options">
    <ul class="dk_options_inner">
    <ul class="dk_options_inner">
<li class="">
<a data-dk-dropdown-value=""> </a>
</li>
<li class="">
<a data-dk-dropdown-value="val1">Text1</a>
</li>
<li class="">
<a data-dk-dropdown-value="val2">Text2</a>
</li>
<li class="">
<a data-dk-dropdown-value="val3">Text3</a>
</li>
    </ul>
    </div>

1 个答案:

答案 0 :(得分:1)

试试这个:

function getName(selectName, selectedValue)
{
var partices = $('#dk_container_'+selectName);
 var selectlbl=partices.find('.dk_label');
 var ul=partices.find('.dk_options_inner');
 $('li').each(function () {
    var elem = $(this);
    if($('a',this).text()== selectedValue){

      elem.addClass('dk_option_current');
      selectlbl.html(selectedValue);
    }
    else{
      elem.attr('class','');
   }
 });
}