为什么第一个将其视为布尔值而第二个不是?
Why first one treat it as boolean value and second not?
我想根据单选按钮切换两个 div 的状态。根据我想切换 div 的可见性的值。首先 div 基于 this.value
显示和隐藏,但第二种情况我使用 !this.value
它不起作用,我也尝试过 !Boolean(this.value)
。
$('[name="radio"]').change(function() {
console.log(this.value,!this.value);
$('#first').toggle(this.value); // this works
$('#second').toggle(!this.value); // this one not
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="radio" value="false" />
<input type="radio" name="radio" value="true" />
<div id="first">1</div>
<div id="second">2</div>
Why first one treat it as Boolean value and second not?
因为 this.value
是一个字符串,'true'
或 'false'
都是真值,所以否定它总是会得到 false
。那就是你的第二个条件永远不会成立
$('[name="radio"]').change(function() {
console.log(this.value, !this.value);
var value = this.value === 'true';
$('#first').toggle(value);
$('#second').toggle(!value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="radio" value="false" />
<input type="radio" name="radio" value="true" />
<div id="first">1</div>
<div id="second">2</div>
另请参阅 toggle()
方法
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
如您所见,value
不是 boolean
类型,因此不考虑它,因为对于 first
,您传递的字符串始终处于切换状态
我想根据单选按钮切换两个 div 的状态。根据我想切换 div 的可见性的值。首先 div 基于 this.value
显示和隐藏,但第二种情况我使用 !this.value
它不起作用,我也尝试过 !Boolean(this.value)
。
$('[name="radio"]').change(function() {
console.log(this.value,!this.value);
$('#first').toggle(this.value); // this works
$('#second').toggle(!this.value); // this one not
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="radio" value="false" />
<input type="radio" name="radio" value="true" />
<div id="first">1</div>
<div id="second">2</div>
Why first one treat it as Boolean value and second not?
因为 this.value
是一个字符串,'true'
或 'false'
都是真值,所以否定它总是会得到 false
。那就是你的第二个条件永远不会成立
$('[name="radio"]').change(function() {
console.log(this.value, !this.value);
var value = this.value === 'true';
$('#first').toggle(value);
$('#second').toggle(!value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="radio" value="false" />
<input type="radio" name="radio" value="true" />
<div id="first">1</div>
<div id="second">2</div>
另请参阅 toggle()
方法
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
如您所见,value
不是 boolean
类型,因此不考虑它,因为对于 first
,您传递的字符串始终处于切换状态