当toggleClass处于活动状态时,jQuery更改值

时间:2018-03-07 20:09:18

标签: jquery

需要有关此方案的帮助。我有一个带“+”按钮的下拉菜单。当它下拉菜单时,我想把它变成“ - ”。当它返回时,它将返回“+”。柔性的。

这就是我的意思:

enter image description here

这是我的jQuery:

<script>
$(document).ready(function() {
 $(".dropdown-toggle").click(function(e) {
        e.preventDefault();
        $('.dropdown-menu').not($(this).next('.dropdown-menu')).fadeOut()
        $(this).next('.dropdown-menu').fadeToggle().toggleClass('isOpen');
        $(".dropdown-toggle").val("-");
    });
});
</script>

这是我的HTML:

<button class="dropdown-toggle" data-toggle="dropdown" href="#">+</button>
  <ul class="dropdown-menu">
   <li class="dropdown-menu-li"><a href="">Test</a></li>
   <li class="dropdown-menu-li"><a href="">Test</a></li>
   <li class="dropdown-menu-li"><a href="">Test</a></li>
   <li class="dropdown-menu-li"><a href="">Test</a></li>    
   <li class="dropdown-menu-li"><a href="">Test</a></li>        
</ul>                                   

非常感谢你帮助我用jquery启发。

2 个答案:

答案 0 :(得分:0)

您需要更改domElement的innerHTML属性而不是value。

document.querySelector(".dropdown-toggle").innerHTML = "-";

jQuery等效于html()函数。

$(".dropdown-toggle").html("-");

如果你愿意:

 console.dir(document.querySelector(".dropdown-toggle"))

然后展开它,你会看到value属性是一个空字符串而innerHTML是“+”

答案 1 :(得分:0)

设置一些基本的 html元素

<button id='dog_button'>Dogs</button>
<div id='hold'></div>

添加样式

body {
  font-family: arial; 
}

button {
  width: 200px;
  height: 40px;
  border: none; 
  border-radius: 3px;
  font-size: 17px;
  font-weight: bold;
  background: gold; 
  border-bottom-left-radius: 0px;
  border-bottom-right-radius: 0px;
  cursor: pointer;
}

.show {
  width: 180px;
  display: inline-block;
  background: #dedede;
  padding: 10px;
}

.square {
  border: 1px solid black;
  width: 20px;
  height: 20px;
  text-align: center;
  float: right;
  padding-top: 3px;
  cursor: pointer;
}

使用 jQuery 根据需要切换类别和选项:

categories_and_ops = {
    'Dog Beds' : ['Soft Dog Beds','Matress Dog Beds','Plastic Dog Beds','3 Peaks','Dog Blankets','Heating Dog Beds', 'Specific Dog Beds', 'Luxury Dog Beds'],
    'Dog Coats' : ['...','...','...','...','...','...', '...', '...']
}

$('#dog_button').click(function() {
$.each(categories_and_ops, function(cat, op) {
div_id = 'div_' + Math.floor(Math.random() * 6);
$('#hold').append("<div class='show' id=" + div_id + "></div><br>")
$('#' + div_id).append("<span style='color:orange; font-weight: bold'>" + cat + "</span><div class='square'>-</div><br>" + '<br>') 
op.forEach(function(op_elem) { $('#' + div_id).append('&nbsp;&nbsp;&nbsp;' + "<span class='ops'>" + op_elem + "</span>" + '<br><br>') })
})
})

$(document).on('click', '.square', function() {
if($(this).html() == '-') {
$(this).parent().children('.ops').toggle();
$(this).html('+');
} else {
$(this).parent().children('.ops').toggle();
$(this).html('-');
}
})

结果

enter image description here

相关问题