2017-02-06 3 views
-1

ボタンにテキストを追加できるように、このスクリプトを変更する方法を教えてください。私はちょうどすべてのテキストの代わりに+または - 記号を追加したいと思います。Javascriptで+/-記号を追加するには?

JACASCRIPT

$(document).ready(function(){ 

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

$(".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()).slideToggle('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()).slideToggle('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()).slideToggle('show'); 
    /* removing this class from the active button */ 
    $dropdownActive.removeClass('dropdown-active'); 
    } 
} 

感謝!

https://jsfiddle.net/jf1zetLw/11/

+0

+または - をどこに追加しますか? – lustoykov

+0

https://jsfiddle.net/jf1zetLw/13/これはあなたが探しているものですか? –

答えて

1

-またはこのような+でそれを置き換えるために-がある場合に、それを置き換えるために+兆候があるかどうかをチェックする必要があります

function changeText(text) { 
    if(text.indexOf('+') >= 0) // if we have a + 
    return text.replace('+', '-'); // return the text after replacing + with - 
    return text.replace('-', '+'); // otherwise return - replaced with + 
} 

それともあなたのような速記を:

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

Working fiddle

+0

すばらしい、感謝イブラヒム! :) –

関連する問題