document.addEventListener("click", function (event) {
// Checking if the button was clicked
if (!event.target.matches("#button")) return;
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Host': 'google-web-search.p.rapidapi.com',
'X-RapidAPI-Key': 'xxxxxxxxxxxxxxxxxxxxxxxxxx'
}
};
fetch('https://google-web-search.p.rapidapi.com/?query=Nike&gl=US&max=10' , options)
.then(response => response.json())
.then(response => rendersearch(response))
.catch(err => console.error(err));
});
function rendersearch(response) {
const setup = document.getElementById("setup");
setup.innerHTML = response.setup;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="sketch.js"></script>
<title>Document</title>
</head>
<body>
<form>
<input id="input" type="text" name="name" value="">
<button id="button" type='button'>Submit</button>
</form>
<p id="setup"></p>
</body>
</html>
我需要使用用戶輸入來查詢一個 api 并在螢屏上顯示搜索結果。我無法將按鈕單擊事件與輸入更改偵聽器連接起來。好心的幫助
document.addEventListener("click", function (event) {
// Checking if the button was clicked
if (!event.target.matches("#button")) return;
};
fetch('https://google-web-search.p.rapidapi.com/?query=Nike&gl=US&max=10' , options)
.then(response => response.json())
.then(response => rendersearch(response))
.catch(err => console.error(err));
});
function rendersearch(response) {
const setup = document.getElementById("setup");
setup.innerHTML = response.setup;
}
當我嘗試搜索時,我變得不確定,但在 console.log 中正確獲取它我不知道可能是什么問題
uj5u.com熱心網友回復:
該物件很可能response不包含名為 的欄位setup,也許您可??以嘗試更改
.then(回應 => 渲染搜索(回應))
到
.then(response => console.log(JSON.stringify(response)))
首先查看您在控制臺中得到的回應,然后將所需欄位傳遞給rendersearch()
uj5u.com熱心網友回復:
您好,我遇到了類似的問題,這就是我發現的解決方案,請注意我如何將變數(按鈕)分配給我希望用戶單擊的東西(按鈕)
然后我使用 button.addEventListener 而不是 document.addEventListener (您可以將按鈕更改為分配給您想要單擊的任何內容的變數,然后它應該可以作業您的問題只是 addEventlistner 函式的語法不正確,沒有其他代碼行似乎不正確
我希望這有幫助
在此處輸入影像描述
uj5u.com熱心網友回復:
你有一個結束標簽};,如果你洗掉它,事件監聽器應該作業。我不知道 API 呼叫是否正常作業。
document.addEventListener("click", function (event) {
// Checking if the button was clicked
if (!event.target.matches("#button")) return;
//delete this one and it should work:
//};
fetch('https://google-web-search.p.rapidapi.com/?query=Nike&gl=US&max=10' , options)
.then(response => response.json())
.then(response => rendersearch(response))
.catch(err => console.error(err));
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/456313.html
標籤:javascript api 点击 dom 事件
