2017-03-27 68 views
-1

裏面的類「我」裏面的「格」的,我有一個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"); 
} 

,但它無法正常工作。我做錯了什麼?

+1

請界定 「_it不working_」。 – Teemu

+0

*什麼*不起作用? – Utkanos

+0

什麼是目標和目標2? – Mazz

回答

1

您可以.toggleClass(class1 class2)簡化此:

function toggleMe(target, target2) { 
    $("#" + target2 + " > div > i").toggleClass('fa-plus-circle fa-minus-circle'); 
    $("#" + target).slideToggle("fast"); 
} 
1

您可以創建一個jQuery插件,使你有效地重用邏輯。

(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');
.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; }
<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>