[英]How can use a conditional statement inside of a function that references the parameter inside of a nested function to return a result in javascript?
[英]return function value inside conditional statement
我有一个带有参数的函数,在函数内部,我有if语句。 当我尝试执行功能时。 它仅在if语句为true时起作用,如果if语句为false则不起作用。
如果我不喜欢使用功能,一切都会很好。 但是,我想改进自己的代码,而不要重复10次。
function PopUpWithText(popUp_img, popUp_txt, popUp_icon) {
var hotspotScale = 1;
if (hotspotScale === 1) {
popUp_img.setAttribute("scale", "0");
popUp_txt.setAttribute("scale", "0");
popUp_icon.setAttribute("scale", "0");
hotspotScale = 0;
} else if (hotspotScale === 0) {
popUp_img.setAttribute("scale", "1");
popUp_txt.setAttribute("scale", "1");
popUp_icon.setAttribute("scale", "1");
hotspotScale = 1;
}
}
var popUpWithText1 = document.querySelectorAll("#popUp_icon1, #AButton");
for (var i = 0; i < popUpWithText1.length; i++) {
popUpWithText1[i].addEventListener("click", function() {
PopUpWithText(
document.querySelector("#popUp_img1"),
document.querySelector("#popUp_txt1"),
document.querySelector("#popUp_icon1")
);
});
}
首先,我知道我肯定会错过return
。 其次,这段代码应该在0和1之间切换小数位。我可以将小数位值更改为0,但随后不会切换回1。
在PopUpWithText
内部,您设置hotspotScale = 1
,因此您的代码将永远不会使用else if
分支。 您可以将其移动到函数范围之外的全局变量。
如果只想在元素上切换可见性,则可以使用visible
属性:
function PopUpWithText(popUp_img, popUp_txt, popUp_icon) {
let visible = popUp_img.getAttribute('visible')
popUp_img.setAttribute("visible", !visible);
popUp_txt.setAttribute("visible", !visible);
popUp_icon.setAttribute("visible", !visible);
}
为了使事情变得容易,您可以将元素扔到父实体:
<a-entity id="parent">
<!-- All three elements --!>
</a-entity>
如果要更改比例,可以执行类似的切换:
function PopUpWithText(popUp_parent) {
let scale = popUp_parent.getAttribute('scale')
scale = scale.x === "1" ? "0" : "1"
popUp_parent.setAttribute("scale", scale);
}
像我一样在这个小提琴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.