[英]javascript autoclick does not seem to autoclick
我真的是 javascript 和 jquery 的新手,我正在嘗試從現有代碼庫中獲取一個自動單擊的按鈕。 即使這是我一直關注的如何自動單擊輸入按鈕,我也無法讓按鈕執行此操作。
代碼如下。 我一直在使用這兩種嘗試.submit()
和.click()
但在start-game-btn
似乎並沒有得到按兩種方式。 每當按下按鈕時,我都會在按鈕中放置一個console.log
並且消息似乎沒有被記錄。
console.log("loading...")
$(() => {
$("#start-game-btn").click(event => {
console.log("start-game")
$("#errors").text("")
event.preventDefault()
const height = parseInt($("#height").val())
const width = parseInt($("#width").val())
const food = parseInt($("#food").val())
let MaxTurnsToNextFoodSpawn = 0
if ($("#food-spawn-chance").val()) {
MaxTurnsToNextFoodSpawn = parseInt($("#food-spawn-chance").val())
}
const snakes = []
$(".snake-group").each(function() {
const url = "http://0.0.0.0:8080/"//$(".snake-url", $(this)).val()
console.log(url)
if (!url) {
return
}
snakes.push({
name: "M1",//$(".snake-name", $(this)).val(),
url
})
})
if (snakes.length === 0) {
$("#errors").text("No snakes available")
}
console.log(12)
fetch("http://localhost:3005/games", {
method: "POST",
body: JSON.stringify({
width,
height,
food,
MaxTurnsToNextFoodSpawn,
"snakes": snakes,
})
}).then(resp => resp.json())
.then(json => {
const id = json.ID
fetch(`http://localhost:3005/games/${id}/start`, {
method: "POST"
}).then(_ => {
$("#board").attr("src", `http://localhost:3009?engine=http://localhost:3005&game=${id}`)
}).catch(err => $("#errors").text(err))
})
.catch(err => $("#errors").text(err))
})
console.log("ready!")
})
window.onload = function(){
var button = document.getElementById('start-game-btn');
button.form.submit();
console.log("Done!!")
}
每次刷新頁面時,日志都會顯示:
loading...
ready!
Done!!
我認為應該記錄的是(或者至少這就是我想要實現的):
loading...
start-game
ready!
Done!!
submit()
不起作用,因為它用於提交表單。
button.form.submit();
不起作用,因為它假定您的按鈕是表單的一部分。
看起來您正在使用 jQuery,請嘗試使用 jQuery 選擇器不帶任何參數調用jQuery click 函數。
例如。
$("#start-game-btn").click();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.