gpt4 book ai didi

javascript - 为什么第一个将其视为 bool 值而第二个不是?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:01:29 24 4
gpt4 key购买 nike

我想根据单选按钮切换两个 div 的状态。基于我想切换 div 可见性的值。第一个 div 显示和隐藏基于 this.value 但第二种情况我使用 !this.value 它不起作用,我也试过 !Boolean(这个值)

$('[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' 都是真值所以取反总是会得到 。那就是你的第二个条件永远不会成立

$('[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 您是传递一个字符串,它总是被切换

关于javascript - 为什么第一个将其视为 bool 值而第二个不是?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36786034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com