gpt4 book ai didi

javascript - 为什么这个 JQuery 仅在我 console.log 一个错误变量时才起作用?

转载 作者:行者123 更新时间:2023-11-28 20:28:52 24 4
gpt4 key购买 nike

我对 jquery 比较陌生,并且试图在每次点击时更改 js Accordion 上的向上和向下箭头,不幸的是,我遇到了一个错误,只有当我 console.log 一个错误的变量时它才起作用。当我 onclick="embiggen(1)"时,是否有人对我可能做错的事情有任何指导,例如,如果它的 Accordion id 是一个?

围绕 html 还存在一些其他问题,但具体来说为什么只有在我 console.log; 时才有效?

function arrowup(id){
$('#downarrow'+id).remove();
$('#dropdown'+id).append('</a>');
$('#dropdown'+id).append('<i id="uparrow'+ id +'" class="icon-1 icon-chevron-up">');
}

function arrowdown(id){
$('#uparrow'+id).remove();
$('#dropdown'+id).append('</a>');
$('#dropdown'+id).append('<i id="downarrow'+ id +'" class="icon-1 icon-chevron-down">');
}


//Switches the arrows
function embiggen(id){

var up = $('#uparrow'+id).length;
if (up == 1){
arrowdown(id);
console.log(i see you);
}
var down = $('#downarrow'+id).length;
if (down == 1){
arrowup(id);
}

}

最佳答案

错误的 console.log() 使其“正常工作”,因为该错误在进入第二个 if 语句之前中断了脚本执行。

<小时/>

解决实际问题

down == 1 始终为 true。您应该使用 else 语句:

if ($('#uparrow'+id).length){
arrowdown(id);
} else if ($('#downarrow'+id).length){
arrowup(id);
}
<小时/>

理解它

down == 1 始终为 true,与 up == 1 无关。以下是两种情况下用伪代码解释的逻辑:

var up = 1, down = 0;
if (up) { down = 1; up = 0; } //enters this block, down now is 1
if (down) { down = 0; up = 1; } //enters this block as down == 1

var up = 0, down = 1;
if (up) { down = 1; up = 0; } //doesn't enter this block
if (down) { down = 0; up = 1; } //enters this block as down == 1

您只需在其中放置一个 else,这样执行流程就不会在第一个 if 语句成功时进入第二个 if 语句。

if (up) {}
else if (down) {}
<小时/>

真值/假值

解释为什么我在条件语句中使用隔离的 .length:在 JavaScript 中,数字 0 是一个假值,而 1 > 是真的,因此可以直接在 if 语句中使用它们,并且它将根据内部 ToBoolean 进行解释。算法逻辑。显然,如果您愿意,您可以 == 1 ,虽然有点多余,但更清晰。

<小时/>

一种可能更简单的方法

有点偏离主题,但您的目标很可能可以通过更简单的方式实现。我可能过于简化了您的逻辑,但根据您的意图,您可以在这两个类之间切换:

function embiggen(id) {
$('#arrow'+id).toggleClass('icon-chevron-up icon-chevron-down');
}

这样,您就不再需要在每次调用函数时创建新的 #downarrow/#uparrow 元素。如果该箭头附加了 JS 行为,您可以使用 hasClass() 通过 if 语句检查要执行的逻辑。 .

关于javascript - 为什么这个 JQuery 仅在我 console.log 一个错误变量时才起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16804400/

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