2017-02-03 46 views
1

如何使加號/減號可點擊?現在不正確... 如果我點擊第二個按鈕時打開,我怎樣才能關閉另一個按鈕(下拉框)?Javascript - 使元素可點擊並關閉其他按鈕

JAVASCRIPT
$(".dropbtn").append('<span class="adl-signs">&nbsp;+</span>'); 

function ctaDropMenu(e) { 
    e.target.nextElementSibling.classList.toggle("show"); 
} 

function toggleSigns(e) { 
    $(e.target).find('.adl-signs').html(function(_, html) { 
    return $.trim(html) == '&nbsp;+' ? '&nbsp;-' : '&nbsp;+'; 
    }); 
} 

$(".dropbtn").click(function(e) { 
    ctaDropMenu(e) 
    toggleSigns(e) 
}); 

// Close the dropdown if the user clicks outside of it 
window.onclick = function(event) { 
    if (!event.target.matches('.dropbtn')) { 

    var dropdowns = document.getElementsByClassName("dropdown-content"); 
    var i; 
    for (i = 0; i < dropdowns.length; i++) { 
     var openDropdown = dropdowns[i]; 
     if (openDropdown.classList.contains('show')) { 
     openDropdown.classList.remove('show'); 
     } 
    } 
    } 
} 

FIDDLE = https://jsfiddle.net/neuhaus3000/jf1zetLw/8/

回答

1

這裏是更新fiddle。我試圖儘可能簡化代碼,並儘可能使用jQuery。

function changeText(text) { 
    return (text.indexOf('+') >= 0) ? 'Click Me -' : 'Click Me +'; 
} 

$(".dropbtn").click(function() { 

    var $this = $(this), 
    $dropdownActive = $('.dropdown-active'); 

    /* changing the text of the active button (if any) */ 
    $dropdownActive.text(changeText($dropdownActive.text())); 

    /* hiding the content under the active button (if any) */ 
    $('.dropdown-content', $dropdownActive.parent()).toggle('show'); 

    if (!$this.hasClass('dropdown-active')) { 

    /* changing the text of the clicked button */ 
    $this.text(changeText($this.text())); 

    /* showing the content under the clicked button */ 
    $('.dropdown-content', $this.parent()).toggle('show'); 

    /* adding this class to the clicked button */ 
    $this.addClass('dropdown-active'); 
    } 

    /* removing this class from the active button */ 
    $dropdownActive.removeClass('dropdown-active'); 
}); 

// Close the dropdown if the user clicks outside of it 
window.onclick = function(event) { 
    if (!event.target.matches('.dropbtn')) { 

    var $dropdownActive = $('.dropdown-active'); 

    /* changing the text of the active button (if any) */ 
    $dropdownActive.text(changeText($dropdownActive.text())); 

    /* hiding the content under the active button (if any) */ 
    $('.dropdown-content', $dropdownActive.parent()).toggle('show'); 

    /* removing this class from the active button */ 
    $dropdownActive.removeClass('dropdown-active'); 
    } 
} 

讓我知道你是否有麻煩。謝謝。

+0

嘿!非常感謝!有一個小問題。當我們點擊打開的下拉按鈕關閉它時,它不會。它不斷重新開放。太感謝了!!!文本將從按鈕到按鈕雖然... :) –

+0

檢查我更新的[小提琴](https://jsfiddle.net/jf1zetLw/11/) –

+0

超級!謝謝!!!關於文本,它將從按鈕到按鈕不同......;)Merci! :) –