我在哪裏最簡單的邏輯是不工作的日子之一。的JavaScript三元運算符工作不正常
當我一個鏈接(id=show-additional-info
)點擊顯示隱藏的內容,我試圖切換圖標的類:
$(document).ready(function(){
$("#show-additional-info").on('click', function() {
console.log('---------------');
var iconToggle = $('#additional-info').attr("aria-expanded");
var active_icon = iconToggle
? 'fa fa-chevron-circle-right'
: 'fa fa-chevron-circle-down';
$('#icon-toggle').attr("class", active_icon);
// show state of trigger event, ternary operator, and affected element class
console.log('additional-info.aria-expanded: ' + iconToggle);
console.log('active_icon: ' + active_icon);
console.log('icon-toggle.class: ' + $('#icon-toggle').attr("class"));
});
});
控制檯日誌顯示第一狀態不確定,這是預期,而應該是falsey。重複點擊後,我看到aria-expanded
屬性在真與假之間切換狀態。但三元運算符不分配值,如我所料:
---------------
additional-info.aria-expanded: undefined
active_icon: fa fa-chevron-circle-down // <-- correctly assigns state.
icon-toggle.class: fa fa-chevron-circle-down
---------------
additional-info.aria-expanded: true
active_icon: fa fa-chevron-circle-right // <-- correctly changes state.
icon-toggle.class: fa fa-chevron-circle-right
---------------
additional-info.aria-expanded: false
active_icon: fa fa-chevron-circle-right // <-- should be circle down!
icon-toggle.class: fa fa-chevron-circle-right
---------------
additional-info.aria-expanded: true
active_icon: fa fa-chevron-circle-right
icon-toggle.class: fa fa-chevron-circle-right
---------------
additional-info.aria-expanded: false
active_icon: fa fa-chevron-circle-right // <-- should be circle down!
icon-toggle.class: fa fa-chevron-circle-right
HTML部分工作正常,並沒有出現參與這個意外的行爲,但爲了完整起見,在這裏它是:
<i id="icon-toggle" class="fa fa-chevron-circle-right" aria-hidden="true"></i> <a id="show-additional-info" href="#additional-info" data-toggle="collapse">Additional Batch Info</a><br><br>
<div>
<ul id="additional-info" class="list-unstyled collapse">
<!-- stuff... --->
</ul>
</div>
對於我的生活,我不明白我在做三元運算符錯了什麼。另一組眼睛將不勝感激!
這是一個更好的解決方案 - 避免不必要的三元完全。 –
更加優雅;謝謝。它不回答我的問題,但它解決了我的問題。 :) +1 –
而且因爲這是一個更好的方式來做到這一點,所以標記爲接受的答案。 –