2017-02-06 1 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

Удивительно, спасибо Ибрагим! :) –