由do while loop by事件生成的类恢复问题



我想检索类,当我点击包含->viewPoster函数中的class="prez_col-'+i +'"。我不知道是因为html()函数还是event,当我点击

时,它阻止我从DOM检索类的名称
template += '<a href="#" id="prez_jaquetteDiv" class="prez_col-' + i + '"><p class="prez_title">' + data[i].title + '</p><img src="' + condJaq + '" class="prez_jaquette" /></a>';
$("#prez_choiseJaq").html(template);

我尝试在模板变量中添加onclick:

template += '<a href="#" onclick="test()" id="prez_jaquetteDiv" class="prez_col-' + i + '"><p class="prez_title">' + data[i].title + '</p><img src="' + condJaq + '" class="prez_jaquette" /></a>';
$("#prez_choiseJaq").html(template);

有一个错误!当其中一个海报显示

HTML文件

<div id="prez_rech" class="prez_rech">
<label for="fname">Recherche du film :</label>
<input type="text" placeholder="Entrez votre film ici" id="prez_input">
<xf:button type="button" id="prez_btn">Rechercher</xf:button>
</div>
<div id="prez_choiseJaq"></div>
<footer class="prez_footer"><a href="https://xenfrench.net">Created by Marilyn</a></footer>
<script type="module" src="js/vendor/prez/prez.js"></script>

File getValue .js

import {array} from './params.js';

const key = array['key'];
const urlMovie = array['urlMovie'];
const noCover = array['noCover'];
const urlImg = array['urlImg'];
const urlJaq = array['urlJaq'];
var jaq = document.getElementById("prez_choiseJaq");
var input = document.getElementById("prez_input");
var myBtn = document.getElementById("prez_btn");
var rech = document.getElementById("prez_rech");
var jaqSelected = $("a.prez_col-" + i);
var data = [];
var inputRep;
var urlNoCover = urlImg + noCover;
var url = urlMovie + key;
var i;
var test = false;
input.addEventListener("keypress", function (event) {
if (event.key === "Enter") {
event.preventDefault();
inputRep = input.value;
getValue();
}
});
myBtn.addEventListener("click", event => {
event.preventDefault();
inputRep = input.value;
getValue();
});

jaqSelected.click(function() {
alert(jaqSelected);
});

async function getValue() {
console.log(inputRep);
try {
const response = await fetch(url + "&language=fr-FR&query=" + inputRep + "&page=1&include_adult=false");
const responseData = await response.json();
data = responseData?.results;
console.log(data);
if (!data.length) {
alert("Le film que vous demandez n'est pas disponible !");
} else {
viewPoster();
}
} catch (error) {
console.log(error);
}
return data;
};
function viewPoster() {
test = false;
if (data) {
var template = "";
jaq.style.display = "inline-grid";
i = -1;
do {
i += 1;
console.log(i);
let condJaq;
if (data[i].poster_path == null) {
condJaq = urlNoCover;
} else {
condJaq = urlJaq + data[i].poster_path;
};
template += '<a href="#" id="prez_jaquetteDiv" class="prez_col-' + i + '"><p class="prez_title">' + data[i].title + '</p><img src="' + condJaq + '" class="prez_jaquette" /></a>';
$("#prez_choiseJaq").html(template);
} while (i < data.length);
};
};
function selected(arg) {
console.log(arg);
};
export { getValue };

文件params.js

var array = {
key: "exemple",
urlMovie: 'https://api.themoviedb.org/3/search/movie?api_key=',
urlSerie: 'https://api.themoviedb.org/3/search/tv?api_key=',
urlImg: 'styles/prez/img/',
urlJaq: "https://image.tmdb.org/t/p/w154",
noCover: "no_cover.jpeg",
};
export { array };

文件prez.js

import { array } from './params.js';
import { getValue } from './getValue.js';

你有什么主意吗?

提前感谢。

这里有很多问题,很难解释为什么你的代码不能工作。for循环的问题是您没有共享的错误的候选,但还有其他错误。

主要的问题是你没有为你的链接添加一个点击处理程序。

我已经从基于模块的JS转换了你的代码(因为我相信这很难在一个代码片段中完成),模拟了Movie API调用并清理了代码以删除大多数不必要的全局变量,更多地利用jQuery,并修复了for循环。

var array = {
key: "exemple",
urlMovie: 'https://api.themoviedb.org/3/search/movie?api_key=',
urlSerie: 'https://api.themoviedb.org/3/search/tv?api_key=',
urlImg: 'styles/prez/img/',
urlJaq: "https://image.tmdb.org/t/p/w154",
noCover: "no_cover.jpeg",
};
function mock_fetch(url, rep) {
const query = url + "&language=fr-FR&query=" + rep + "&page=1&include_adult=false"
// response = await fetch(query);
// return await reponse.json()
return { results: [{ poster_path: "This is the poster path"
, title: rep
}
,{ poster_path: "Some other path"
, title: "Some other movie"
}
]
}
}
var data; // this will hold whatever data retrieved by the last query to the movie API (may be null/undefined)
async function getValue(inputRep) {
try {
const responseData = mock_fetch(array.urlMovie + array.key, inputRep);
data = responseData?.results;
if (!data.length) {
alert("Le film que vous demandez n'est pas disponible !");
} else {
viewPoster(data);
}
} catch (error) {
console.error(error);
}
return data;
};
function viewPoster() {
$("#prez_choiseJaq").css("display", "inline-grid");
var template = "";
data.forEach( (film, index) => {
template += `<a href="#" id="prez_jaquetteDiv" class="prez_col" data-index=${index}><p class="prez_title">${film.title}</p><img src="${film.poster_path?(array.urlJaq + film.poster_path):array.urlImg+array.noCover}" class="prez_jaquette" /></a>`;
})
$("#prez_choiseJaq").html(template);
};
function selectMovie(event) {
event.preventDefault();
getValue($('#prez_input').val());
}
function doSomethingWithFilm(event) {
let index = $(this).data('index');
console.log(`The index you clicked was ${index}`)
if (data && data[index]) {
console.log(`The data for that index is ${JSON.stringify(data[index])}`)
} else {
console.log(`The data for that index is not available`)
}
}
function init() {
$('#prez_input').keypress(event => { event.key === "Enter" && selectMovie(event) });
$('#prez_btn').on("click", selectMovie);
// Add the click handler for the links as a delegate because the links do not exist at the time this code is executed
$(document).on("click", ".prez_col", doSomethingWithFilm);
}
$(init)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</script>
</head>
<body>
<div id="prez_rech" class="prez_rech">
<label for="fname">Recherche du film :</label>
<input type="text" placeholder="Entrez votre film ici" id="prez_input">
<xf:button type="button" id="prez_btn">Rechercher</xf:button>
</div>
<div id="prez_choiseJaq"></div>
</body>
</html>

您的do {} while ()循环条件正在尝试循环一个超出您的数据数组。问题在于如何设置和自增迭代器变量:i

在循环之前将迭代器设置为i = -1;,然后在循环中首先将其自增:i += 1;,并将while条件设置为当i等于数组长度:while ( i < data.length )时停止循环。如果数组只有一个元素,则i必须为1才能停止循环。在第一轮结束时,i等于0。即使在单个数组元素的情况下,它仍然小于数组的长度,因此循环将再次循环。一个元素,两个循环。两个元素,三个循环。三个元素,四个循环,等等

简单的修复方法是:

while (i < data.length);

…:

while (i < data.length - 1);

let data = ['a','b','c','d','e'];
// ALWAYS ONE TO MANY LOOPS
let i = -1;
do {
i += 1;
console.log(i, data[i]);
} while (i < data.length);
// EASY FIX
i = -1;
do {
i += 1;
console.log(i, data[i]);
} while (i < data.length - 1); // <-- reduce length by one

// BETTER YET
i = 0;
do {
console.log(i, data[i]);
i += 1; // <-- move iterator increment to end of loop
} while (i < data.length);


如何使用迭代器变量控制循环:

不管你使用什么类型的循环:for,while,do while,当你需要一个时,使用你的循环迭代器对我来说更有意义,如:

let data = [1,2,3,4,5,6];
let ii = 0;
do {
console.log(ii, data[ii]);
ii++;
} while ( ii < data.length );

循环前,设置ii0。循环开始时,使用ii作为0,然后在循环结束时增加ii。每个元素都被访问,并且只被访问一次。


这里的函数(简单的固定),你的do {} while ()循环是:

function viewPoster() {
test = false;
if (data) {
var template = "";
jaq.style.display = "inline-grid";
i = -1;
do {
i += 1;
console.log(i);
let condJaq;
if (data[i].poster_path == null) {
condJaq = urlNoCover;
} else {
condJaq = urlJaq + data[i].poster_path;
};
template += '<a href="#" id="prez_jaquetteDiv" class="prez_col-' + i + '"><p class="prez_title">' + data[i].title + '</p><img src="' + condJaq + '" class="prez_jaquette" /></a>';
$("#prez_choiseJaq").html(template);
} while (i < data.length - 1);
};
};

最新更新