gpt4 book ai didi

javascript - 通过传递 jquery 变量切换按钮

转载 作者:行者123 更新时间:2023-12-03 06:41:38 24 4
gpt4 key购买 nike

我的 html 中有:

<input type="button" value="Start L/D" id="start_ld" name="start_ld" onclick='return(toggle_server_create("start_ld", "stop_ld", false));' />
<input type="button" value="Stop L/D" id="stop_ld" name="stop_fx_ld" style="display:none;" onclick='return(toggle_server_create("start_ld", "stop_ld", true));' />

在我的 javascript/jquery 中:

  function toggle_server_create (start_id, stop_id, state){
var query = '#' + start_id +',' + '#' + stop_id;
var query_stop = '#' + stop_id
var query_start = '#' + start_id
// console.log(state);
// console.log(query_stop);

$(query).click(function() {
// console.log(query_start);
// console.log (this.name);
if ((this.name === start_id) && $(this).is(":visible") && state==false) {
console.log("Show stop")
$(query_stop).show();
}
else if ((this.name === stop_id) && $(this).is(":visible") && state == true) {
console.log("Show start")
$(query_start).show();
}

$(this).hide();

});
}

toggle_server_create 应该接受 jQuery 变量并相应地在启动和停止之间切换。然而,它并不是这样工作的,而是必须单击两次才能看到按钮发生变化,再次单击时它就会消失。我是 JavaScript 新手,不知道如何解决这个问题。

最佳答案

您的问题是仅在用户单击按钮后设置单击处理程序的结果。单击按钮后,toggle_server_create 就会运行。当它运行时,它会为两个按钮创建一个单击处理程序,其中显示:“当您单击此按钮时,执行此函数中的所有内容。

因此,第一次执行此操作时,仅设置查询变量,然后创建一个单击处理程序,只要设置其中一个按钮,该处理程序就会执行。这就是为什么您第二次单击它会起作用。

代码有点困惑,所以我不能 100% 确定您想要完成什么,但这就是导致它只在第二次单击时运行的原因。

如果您确实想在按钮之间切换,请考虑以下内容:https://jsfiddle.net/bb14xn7z/1/

你的 html 位置:

<input type="button" value="Start L/D" id="start_ld" name="start_ld"/>
<input type="button" value="Stop L/D" id="stop_ld" name="stop_fx_ld" style="display:none;"/>

你的 JavaScript 是:

$(function() {
$("#start_ld").click(function() {
$(this).hide();
$("#stop_ld").show();
});

$("#stop_ld").click(function() {
$(this).hide();
$("#start_ld").show();
});
});

请注意我如何不在 html 中设置 onclick,而是在页面加载时在 javascript 中设置点击处理程序。

关于javascript - 通过传递 jquery 变量切换按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37931873/

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