Javascript EventListener和元素选择器问题



长话短说,我有一个JavaScript选择器问题。

我有一个循环,它创建了几个元素,每个元素都有相同的按钮和不同的输入值。单击按钮需要将关联的输入值增加1,然后更改纵横比(在+1和-1之间切换(。

我的问题是,点击一个按钮会改变所有按钮的外观,并增加最后一个输入值的值,而不是它的关联值。

我已经尝试将[I]与选择器一起使用,以及使用getElementsByNames等。

解释清楚似乎并不容易,这可能会有所帮助:https://codepen.io/enukeron/pen/qBaZNbb

谢谢你能提供的任何帮助。

HTML:

<div class="photoGrid">  </div>

Javascipt:

const PhotographeID= 82; 
var jsonFile =  {
"media": [
{ "photographerId": 82, "likes": 82, },
{ "photographerId": 82, "likes": 62, }
]}

const photoLikes= document.getElementById ('photoLikes');
var photoGrid  = document.getElementsByClassName('photoGrid')[0];
var heart=  document.getElementById('heart');
var imageCard  = document.getElementsByClassName('imageCard')[0];
function findId(jsonFile, idToLookFor) {
var media = jsonFile.media;
for (var i = 0; i < media.length; i++) {
if (media[i].photographerId == idToLookFor) {

// Creating Dom Elements
var imageCard = document.createElement('div');
imageCard.classList.add('imageCard');
photoGrid.appendChild(imageCard);

var photoInfos = document.createElement('div');
photoInfos.classList.add('photoInfos');
imageCard.appendChild(photoInfos);   

var photoLikes = document.createElement('input');
photoLikes.classList.add('photoLikes');
photoLikes.setAttribute("type", "number");
photoLikes.setAttribute("value", media[i].likes);
photoLikes.readOnly = true;
photoInfos.appendChild(photoLikes);        

var heart = document.createElement('span');
heart.classList.add('heart');
heart.classList.add(i);
photoInfos.appendChild(heart);   

var faHeart= document.createElement('i');
faHeart.classList.add('fa');
faHeart.classList.add('fa-heart-o');
faHeart.setAttribute("aria-hidden", "true" );
faHeart.setAttribute("id", "faHeart");
heart.appendChild(faHeart);


// like button functions 
var heartI= document.getElementsByClassName(i);

heart.addEventListener('click', (event) => {
if( heart.classList.contains("liked")){
$(".heart").html('<i class="fa fa-heart-o" aria-hidden="true"></i>');
heart.classList.remove("liked");

/*Removes 1 like */
var value = parseInt(photoLikes.value, 10);
value = isNaN(value) ? 0 : value;
value--;
photoLikes.value = value;  
}

else{
$(".heart").html('<i class="fa fa-heart" aria-hidden="true"></i>');
heart.classList.add("liked");

/*adds 1 like */
var value = parseInt(photoLikes.value, 10);
value = isNaN(value) ? 0 : value;
value++;
photoLikes.value = value; 
}
});
; } } }
findId(jsonFile, PhotographeID);

Soooo,我让每件事都运转起来:https://codepen.io/enukeron/pen/qBaZNbb?editors=1010

  1. 正如@kaiLehmann所指出的,计数问题是由于误用了Var而不是Const
  2. 按钮一起变化的原因是使用了:

$(".heart").html('<i class="fa fa-heart" aria-hidden="true"></i>');

而不是heart.innerHTML='<i class="fa fa-heart" aria-hidden="true"></i>';

我不知道为什么,如果有人能解释其中的区别,希望一个是纯JS,另一个是Jquery,那就太好了!

最新更新