document.querySelector 没有选择类
2021-09-26
66
我似乎无法让它工作
app.js
:
const api = 'xxxxxxxx';
function ySearch(e) {
const url = 'https://www.googleapis.com/youtube/v3/search/?
part=snippet&key='+api+'&q=test&maxResults=20';
document.querySelector('.output').textContent = url;
}
html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text">
<button>Search</button>
<div class="output"></div>
<script src="app.js"></script>
</body>
</html>
预期:当我重新加载
html
时,我可以看到
url
值。
但是由于某种原因,输出类
div
未被填充。可能出了什么问题?
2个回答
您没有调用该函数:
const api = 'xxxxxxxx';
function ySearch(e) {
const url = 'https://www.googleapis.com/youtube/v3/search/?part=snippet&key=' + api + '&q=test&maxResults=20';
document.querySelector('.output').textContent = url;
}
const button = document.querySelector('button');
button.addEventListener('click', ySearch)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text">
<button>Search</button>
<div class="output"></div>
</body>
</html>
Spectric
2021-09-26
您需要调用
ySearch
来运行它,因此您需要在按钮上监听一个事件来处理点击:
function ySearch(e) {
const url = 'https://...';
document.querySelector('.output').textContent = url;
}
// add event listener to button
document.getElementById('searchButton').addEventListener('click', ySearch)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="app.js" async defer></script>
</head>
<body>
<input type="text">
<button id="searchButton" >Search</button>
<div class="output"></div>
</body>
</html>
Cristofer Villegas
2021-09-26