根据参数值禁用下拉列表选项

时间:2016-03-09 10:49:05

标签: jquery drop-down-menu

我有以下代码。我希望value==0会自动禁用第二个选项。我知道我可以通过在disabled标记内添加类<li>来禁用该选项,但是如何根据参数值添加此类?

function analysisActions(key, value){

  var str= '<div class="dropdown">' +
      '<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Actions '+
      '<span class="caret" style="border-top:4px solid white"></span></button>'+
      '<ul class="dropdown-menu">'+
        '<li><a href="#" data-target="#A_form" data-toggle="modal" class="open-AddBookDialog" data-id="' + key +'" id="a_' + key + '">A</a></li>'+
        '<li><a href="#" data-target="#B_form" data-toggle="modal" class="open-AddBookDialog" data-id="' + key +'" data-id="' + key + '" id="b_' + key + '">B</a></li>'+
      '</ul>'+
    '</div>';

return str;
}

2 个答案:

答案 0 :(得分:2)

在将use if value == 0添加到字符串之前,它是简单的li。如果value == 0添加了类class="disabled"

  var str = '<div class="dropdown">' +
  '<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Actions ' +
  '<span class="caret" style="border-top:4px solid white"></span></button>' +
  '<ul class="dropdown-menu">' +
    '<li><a href="#" data-target="#A_form" data-toggle="modal" class="open-AddBookDialog" data-id="' + key + '" id="a_' + key + '">A</a></li>';
        if (value == 0) {
            str += '<li class="disabled"><a href="#" class="open-AddBookDialog" data-id="' + key + '" data-id="' + key + '" id="b_' + key + '">B</a></li>';
        }
        else {
            str += '<li><a href="#" data-target="#B_form" data-toggle="modal" class="open-AddBookDialog" data-id="' + key + '" data-id="' + key + '" id="b_' + key + '">B</a></li>';
        }
        str += '</ul>' +
'</div>';

答案 1 :(得分:2)

 function analysisActions(key, value) {

    var disabledStr = value == 0 ? ' class="disabled" ' : '';
    var disable = value == 0 ? ' disabled' : '';

    var str = '<div class="dropdown">' +
        '<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Actions ' +
        '<span class="caret" style="border-top:4px solid white"></span></button>' +
        '<ul class="dropdown-menu">' +
        '<li><a href="#" data-target="#A_form" data-toggle="modal" class="open-AddBookDialog" data-id="' + key + '" id="a_' + key + '">A</a></li>' +
        '<li' + disabledStr + '><a ' +  disable  + ' href="#" data-target="#B_form" data-toggle="modal" class="open-AddBookDialog" data-id="' + key + '" data-id="' + key + '" id="b_' + key + '">B</a></li>' +
        '</ul>' +
        '</div>';

    return str;
}