あなただけの必要なクラスを切り替えることtoggleClass
を使用し、その後、あなたのinput
にinput
イベントにフックする必要があります。
$('#status_action').on('input', function(){
// get the number value, or 0 from the input
var value = parseInt($(this).val(), 10) || 0;
if(value === 0){ // if our value is strictly equal to 0
// find all closed envelopes, and toggle their classes to open
$('#status_alert .fa-envelope-o').toggleClass('fa-envelope-o fa-envelope-open-o');
}else{ // otherwise
// find all open envelopes, and toggle their classes to closed
$('#status_alert .fa-envelope-open-o').toggleClass('fa-envelope-o fa-envelope-open-o');
}
})
JSFIDDLE
UPDATE
あなたは後に読み取り専用の入力を更新するために、コードの別の部分を使用して終了機会に、再利用可能な機能にこれを変換しますページの読み込みが完了しました
HTML
<a href="javascript:void(0)" id="status_alert" class="btn btn-success btn-xs">
<i class="fa fa-envelope-o" aria-hidden="true"></i> <span>unread</span>
</a>
JS
var toggleEnvelopeIcon = function(){
// get the number value, or 0 from the input
var value = parseInt($('#status_action').val(), 10) || 0;
if(value === 0){ // if our value is strictly equal to 0
// find all closed envelopes, and toggle their classes to open
$('#status_alert .fa-envelope-o').toggleClass('fa-envelope-o fa-envelope-open-o');
$('#status_alert span').text('read');
}else{ // otherwise
// find all open envelopes, and toggle their classes to closed
$('#status_alert .fa-envelope-open-o').toggleClass('fa-envelope-o fa-envelope-open-o');
$('#status_alert span').text('unread');
}
}
$('#status_action').on('input', toggleEnvelopeIcon);
toggleEnvelopeIcon();
Updated JSFIDDLE
CSS + JSのOPTION
、私は私のJSにテキスト値を置くことを心配する必要はいけないこの方法(doesntのを個人的に
、私はこのオプションを好む、私はむしろJSは、単一のクラスを切り替えるだろう、とCSS正しいアイコン/テキストの表示/非表示を扱いますロジックのものでビューコードについて私と一緒に座ってください)。
HTML
<a href="javascript:void(0)" id="status_alert" class="btn btn-success btn-xs has-unread">
<span class="show-if-unread"><i class="fa fa-envelope-o" aria-hidden="true"></i> unread</span>
<span class="show-if-read"><i class="fa fa-envelope-open-o" aria-hidden="true"></i> read</span>
</a>
CSS
.has-read .show-if-read,
.has-unread .show-if-unread{
display:inline-block;
}
.has-read .show-if-unread,
.has-unread .show-if-read{
display:none;
}
var toggleEnvelopeIcon = function(){
// get the number value, or 0 from the input
var value = parseInt($('#status_action').val(), 10) || 0;
if(value === 0){ // if our value is strictly equal to 0
// toggle alert classes
$('#status_alert').removeClass('has-unread').addClass('has-read');
}else{ // otherwise
// toggle alert classes
$('#status_alert').removeClass('has-read').addClass('has-unread');
}
}
JS
何が起こっているのですか? – guradio
実用サンプルを提供していますか? 'FA-エンベロープo'を使用して –
@guradio、何も、クラス変わらない –