gpt4 book ai didi

javascript - jQuery 切换函数隐藏可见元素,即使参数是真实的

转载 作者:太空宇宙 更新时间:2023-11-04 00:36:18 25 4
gpt4 key购买 nike

This question相似但无济于事。

jQuery 文档表明 $.toggle function接受一个 bool 参数:

The second version of the method accepts a Boolean parameter. If this parameter is true, then the matched elements are shown; if false, the elements are hidden.

但是,传递真值(非 bool 值)似乎无法识别。下面的代码在显示/隐藏红色框之间交替,即使 toggle 函数被传递了一个真值。

为什么真值不起作用?

var imageURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABBoAAAK8CAYAAABBSdyWAAAgAElEQVR4Ady9+bMcyXHn6ZWZdbwbaDSAvthNiocoiuRobU2/6P//ZW3X1mZNGo6GktjsE2gAD8c76q7Ktc/X41uZr/DQYLObnNEEUC8y4/Tw8PDw8PCIHPzmt//QRs9tBhFtm0H4g8FgF+vwqqrCv/V6rfh+ul2GP+FhsM387XYQbTuISlVXUdd11";

$(document).ready(function() {
$(".box").on("click", function() {
$("#redBox").toggle(imageURL);
$("#curURL").text(imageURL);
});
});
.box {
position: fixed;
width: 200px;
height: 200px;
background: red;
cursor: pointer;
}

#redBox {
background: red;
}

#blueBox {
background: blue;
}

#curURL {
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="blueBox" class="box"></div>
<div id="redBox" class="box"></div>

<div id="curURL"></div>

Codepen Mirror

最佳答案

除了按照@MattU 的建议使用双非运算符 (!!) - 您还可以使用 Boolean(imageURL)..

var imageURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABBoAAAK8CAYAAABBSdyWAAAgAElEQVR4Ady9+bMcyXHn6ZWZdbwbaDSAvthNiocoiuRobU2/6P//ZW3X1mZNGo6GktjsE2gAD8c76q7Ktc/X41uZr/DQYLObnNEEUC8y4/Tw8PDw8PCIHPzmt//QRs9tBhFtm0H4g8FgF+vwqqrCv/V6rfh+ul2GP+FhsM387XYQbTuISlVXUdd11";

$(document).ready(function() {
$(".box").on("click", function() {
$("#redBox").toggle(Boolean(imageURL));
$("#curURL").text(imageURL);
});
});
.box {
position: fixed;
width: 200px;
height: 200px;
background: red;
cursor: pointer;
}

#redBox {
background: red;
}

#blueBox {
background: blue;
}

#curURL {
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="blueBox" class="box"></div>
<div id="redBox" class="box"></div>

<div id="curURL"></div>

关于javascript - jQuery 切换函数隐藏可见元素,即使参数是真实的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59340058/

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