gpt4 book ai didi

javascript - 将值从我的 .click() 函数传递到 if 语句

转载 作者:行者123 更新时间:2023-11-28 17:16:03 28 4
gpt4 key购买 nike

我有这个html代码

<p id = "line1"> You are in a field </p>
<button id = "btn1"> [ Go to cave ] </button>

以及使用 jQuery 的 JavaScript 代码

var bar = 0;  
$(document).ready(function(){
$("#btn1").click(function(){
console.log("Going to cave entrance");
bar = 1;
});
if (bar){
console.log("At entrance");
$("#line1").html("Go into cave?");
$("#btn1").html("Yes!!");
}
else{
console.log("I am error");
}
});

如您所见,我有一个将变量 bar 设置为 1 的按钮和一个等待 bar 为 1 的 if 语句。但是,当我单击该按钮时,if 语句永远不会执行。

变量 bar 设置为 1 并打印 console.log("Going to Cave Entry"),但没有执行任何其他操作。

这就像执行卡在.click()函数中一样。

最佳答案

简而言之,一旦 DOM 准备好(即在用户有机会单击按钮之前),您的 if 逻辑就会运行,因为您已将其直接放置在 JQuery 的文档中.ready回调函数:

$(document).ready(function(){
// Anything here will execute one time, when the DOM is fully parsed
});

为了让 if 逻辑在单击按钮后的某个时刻运行,需要将其放入一个可以在您需要时随时调用的函数中:

function testButton(){
if (bar){
console.log("At entrance");
$("#line1").html("Go into cave?");
$("#btn1").html("Yes!!");
} else{
console.log("I am error");
}
}

但是,真正的问题是这个函数应该什么时候运行?在单击按钮后立即运行它是没有意义的,因为在 click 事件中按钮的处理程序中,bar 变量手动设置为 1。如果您在单击后立即调用测试函数,它将始终进入测试的 true 分支。

如果您正在寻找一种方法来跟踪玩家去过的地方,更好的方法是设置这些位置的数组,并在用户移动时检查该数组。

所以,最后,您需要像下面这样设置代码:

var visitedPlaces = [];  // Store visited places here

$(document).ready(function(){
// When any of the location change buttons get clicked...
$(".changeLocation").click(function(){
// Extract the location from the data-* attribute of the clicked button
var newLocation = $(this).data("location");

// Test to see if player has already gone here
if (testLocation(newLocation)){
console.log("You've already been to the " + newLocation + "!");
} else {
console.log("Entering " + newLocation + "!");
}

visitedPlaces.push(newLocation); // Record that player has been to cave
});
});

// Call this function anytime you need to test the bar variable:
function testLocation(loc){
// Check if the location is already in the array and return true/false as appropriate
return (visitedPlaces.indexOf(loc) > -1) ? true : false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id = "line1"> You are in a field </p>
<!-- Use data-* attributes to signal where the user is going -->
<button class="changeLocation" data-location="cave">[ Go to cave ]</button>
<button class="changeLocation" data-location="inn">[ Go to inn ]</button>
<button class="changeLocation" data-location="mountains">[ Go to mountains ]</button>

关于javascript - 将值从我的 .click() 函数传递到 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53488903/

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