2017-02-23 7 views
1

私は、再度クリックすると、クリックして戻るときに+ Expandから- Closeにテキストを変更する機能を持っています。これは本当に基本的な解決策です。 .html()にあるすべてのものを編集することなく、+-にCSSを追加したいと思っています。私はスパンを追加しようとしましたが、うまくいかないようです。それをどうやってやるの?クリックして前後に切り替える

JavaScriptが

$('.displaybutton').click(function(){ 
    $('#otherResponseList').toggle(); 
     if($(this).html() == '- Close'){ 
      $(this).html('+ Expand'); 
     } else { 
      $(this).html('- Close'); 
    } 
}); 

答えて

1

それはあなたがcontent財産と::after擬似セレクタをしたいように聞こえます。あなたはjQueryのを使用することができるしている場合はJavaScriptに関しては、toggleClass機能はワンライナーです:

$('.toggle').click(function(){ 
 
    $(this).toggleClass('isOpen') 
 
});
.toggle{ 
 
    border:1px solid black; 
 
    cursor:pointer; 
 
    padding: 5px; 
 
} 
 
.toggle::after { 
 
    content:"+ expand"; 
 
} 
 
.toggle.isOpen::after { 
 
    content:"- close"; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<span class="toggle"></span>

0

あなたは、コンテンツから+-を分離し、中にすべてのものを維持することができます擬似セレクタを使用してCSS。 CSSでターゲティングできるJS内のクラスを切り替えるだけです。

document.getElementById('button').addEventListener('click',function() { 
 
    document.getElementById('div').classList.toggle('close'); 
 
})
.expand:before { 
 
    content: '+'; 
 
    color: green; 
 
} 
 
.expand:after { 
 
    content: 'expand'; 
 
} 
 
.close:before { 
 
    color: red; 
 
    content: '-'; 
 
} 
 
.close:after { 
 
    content: 'close'; 
 
}
<div id="div" class="expand"></div> 
 
<button id="button">click</button>

関連する問題