javascript - 如何将链接添加到图像或标题?
问题描述
我正在尝试在图像或标题上添加链接。当我单击图像/文本时,它应该将我带到另一个页面 index.html。
我怎样才能做到这一点?
const apiUrl = 'https://api.themoviedb.org/3/discover/movie
sort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1;
const IMGPATH = "https://image.tmdb.org/t/p/w1280";
const SEARCHAPI = "https://api.themoviedb.org/3/search/movie?
&api_key=04c35731a5ee918f014970082a0088b1&query=";
const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");
showMovies(apiUrl);
function showMovies(url){
fetch(url).then(res => res.json())
.then(function(data){
console.log(data.results);
data.results.forEach(element => {
const el = document.createElement('div');
const image = document.createElement('img');
const text = document.createElement('h2');
text.innerHTML = `${element.title}`;
image.src = IMGPATH + element.poster_path;
el.appendChild(image);
el.appendChild(text);
main.appendChild(el);
});
});
}
form.addEventListener("submit", (e) => {
e.preventDefault();
main.innerHTML = '';
const searchTerm = search.value;
if (searchTerm) {
showMovies(SEARCHAPI + searchTerm);
search.value = "";
}
});
解决方案
修复了您的代码,勾选是添加一个元素而不是所需的 href
const apiUrl =
"https://api.themoviedb.org/3/discover/moviesort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1";
const IMGPATH = "https://image.tmdb.org/t/p/w1280";
const SEARCHAPI =
"https://api.themoviedb.org/3/search/movie? &api_key=04c35731a5ee918f014970082a0088b1&query=";
const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");
showMovies(apiUrl);
function showMovies(url) {
fetch(url)
.then((res) => res.json())
.then(function (data) {
console.log(data.results);
data.results.forEach((element) => {
el = document.createElement("a");
el.href = "https://example.com"
const image = document.createElement("img");
const text = document.createElement("h2");
text.innerHTML = `${element.title}`;
image.src = IMGPATH + element.poster_path;
el.appendChild(image);
el.appendChild(text);
main.appendChild(el);
});
});
}
form.addEventListener("submit", (e) => {
e.preventDefault();
main.innerHTML = "";
const searchTerm = search.value;
if (searchTerm) {
showMovies(SEARCHAPI + searchTerm);
search.value = "";
}
});
推荐阅读
- r - R包'word2vec'doc2vec函数
- sql - 使用返回 2465 的 SQL 使用 VBA 过滤表单找不到“|1”
- google-cloud-platform - 多环境 terragrunt gcp 项目的模板?
- python - 为什么 neo4j python 驱动官方文档中的代码示例不起作用?
- arm - STM32F103 clang 编译和大二进制大小
- javascript - 使用 CryptoJS 进行 OpenSSL 加密解密
- ballerina - 如何在 Ballerina 中将 int 转换为没有 stdlib 的字符串?
- node.js - 如何延迟将图像上传到 S3?
- google-sheets - 是否可以让表格将我的 REGEXEXTRACT 结果识别为日期?
- powershell - diskpart 可以带命令行参数吗?或者我可以用 powershell 伪造它们吗?