如何更改" i"里面" div"在目标元素内

时间:2017-03-27 10:32:52

标签: javascript jquery

我有一个HTML

<div class="panel-heading" onclick="toggleMe('<?php echo $warehouse['country']; ?>1', '<?php echo $warehouse['country']; ?>')">
    <span class="panel-title">  Warehouse Address <span><?php echo $warehouse['country']; ?></span>
        <div class="panel-title-right"><i class="fa fa-plus-circle" aria-hidden="true" id="usa"></i>
        </div>
    </span>
</div>

我的js函数是

function toggleMe(target, target2) {
    if ($("#" + target2 + " > div > i").attr('class') == 'fa fa-plus-circle') {
        $("#" + target2 + " > div > i").removeClass('fa fa-plus-circle').addClass('fa fa-minus-circle');
    } else {
        $("#" + target2 + " > div > i").removeClass('fa fa-minus-circle').addClass('fa fa-plus-circle');
    }
    $("#" + target).slideToggle("fast");
}

但它不起作用。我做错了什么?

2 个答案:

答案 0 :(得分:1)

您可以使用 Current AVG Price Sum Price AVG Price

简化此操作
.toggleClass(class1 class2)

答案 1 :(得分:1)

您可以创建一个jQuery插件,使您能够有效地重用逻辑。

&#13;
&#13;
(function($) {
  $.fn.swapClass = function(classA, classB, child) {
    var $this = this;
    $this.toggleClass(classA + ' ' + classB).next(child).slideToggle('fast');
    return $this;
  };
})(jQuery);

$('.fa-plus-circle, .fa-minus-circle').on('click', function(e) {
  $(e.target).swapClass('fa-plus-circle', 'fa-minus-circle', 'div');
}).trigger('click').first().trigger('click').next('div').find('i').first().trigger('click');
&#13;
.fa-plus-circle  { color: #070; }
.fa-minus-circle { color: #D00; }
.fa-plus-circle:hover, .fa-minus-circle:hover {
  cursor: pointer;
}
ul { list-style: none; margin-left: -24px; }
&#13;
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li><i class="fa fa-plus-circle"></i>
    <div class="child-node">
      <ul>
        <li><i class="fa fa-plus-circle"></i> <div class="child-node">A</div></li>
        <li><i class="fa fa-plus-circle"></i> <div class="child-node">B</div></li>
        <li><i class="fa fa-plus-circle"></i> <div class="child-node">C</div></li>
      </ul>
    </div>
  </li>
  <li><i class="fa fa-plus-circle"></i> <div class="child-node">D</div></li>
  <li><i class="fa fa-plus-circle"></i> <div class="child-node">E</div></li>
  <li><i class="fa fa-plus-circle"></i> <div class="child-node">F</div></li>
</ul>
&#13;
&#13;
&#13;