اذهب إلى المحتوى
  • 0

جعل الكود يعمل على جميع أيقونات LIKE جافاسكربت؟

محمد لارافيل

السؤال

لدي كود js يعمل ، لكن المشكلة هي أنه عندما أستخدمه في صفحة HTML الرئيسية ، فإنه لسبب ما يعمل فقط على الصورة الأولى ، على الرغم من أن أيقونة LIKE موجودة في جميع الصور. لا أفهم سبب عمله فقط على الأيقونة الأولى ولا يعمل على الأيقونات الأخرى

const likeIcon = document.getElementById('like-icon');
const likeCount = document.getElementById('like-count');


likeIcon.onclick = () => {
    const newId = likeIcon.getAttribute('data-news');
    const url = `/like_news/${parseInt(newId)}/`;
    fetch(url, {
        method: 'GET',
        headers: {
            'Content-type': 'applicatin/json'
        }
    })
    .then(response => {
        return response.json();
    })
    .then(data => {
        if(data.liked) {
            likeIcon.classList.remove('empty-heart');
        }
        else {
            likeIcon.classList.add('empty-heart');
        }
        likeCount.innerHTML = data.like_count;
    })
    .catch(error => {
        console.log(error);
    })
}

كود HTML

<section class="trend">
    <div class="container">
      <div class="flex align-center justify-between trend-header">
        <h2 class="subtitle">
          <i class="ri-fire-line subtitle-icon"></i>
          В тренде
        </h2>
        <button class="btn btn-outline">Посмотреть все</button>
      </div>

      <div class="trend-content">
        {% for new in news|slice:"2" %}
        <div class="trend-card">
          <img src="{{new.banner.url}}" alt="newsPhoto" class="trend-background" />
          <div class="card-header">{{new.category.title}}</div>
          <div class="card-bottom">
            <h3 class="card-title">
              {{new.title}}
            </h3>
            <div class="card-btn">
              <div class="count" id="like-count">{{new.likes.count}}</div>
              {% if liked_by %}
              <button class="btn-up" class="fa fa-heart">
                <li><a href="javascript:void(0);"><i id="like-icon" data-news="{{new.id}}" class="fa fa-heart"></i></a></li>
              </button>
              {% else %}
              <button class="btn-up" class="fa fa-heart empty-heart">
              <li><a href="javascript:void(0);"><i id="like-icon" data-news="{{new.id}}" class="fa fa-heart empty-heart"></i></a></li>
            </button>
            </div>
            {% endif %}
          </div>
        </div>
        {% endfor %}
      </div>
    </div>
  </section>

حاولت استخدام querySelectorAll ولكن لم ينجح أيضا

const likeIcon = document.querySelectorAll('#like-icon');
const likeCount = document.getElementById('like-count');
likeIcon.forEach(like-icon => {
    like-icon.addEventListener("click", () => { 
      const newId = likeIcon.getAttribute('data-news');
    const url = `/like_news/${parseInt(newId)}/`;
    fetch(url, {
        method: 'GET',
        headers: {
            'Content-type': 'applicatin/json'
        }
    })
    .then(response => {
        return response.json();
    })
    .then(data => {
        if(data.liked) {
            likeIcon.classList.remove('empty-heart');
        }
        else {
            likeIcon.classList.add('empty-heart');
        }
        likeCount.innerHTML = data.like_count;
    })
    .catch(error => {
        console.log(error);
    })
          });
      }
}

كيف أجعلها تعمل على جميع أيقونات LIKE؟

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 0

أظن ان المشكلة في الكود هي أنه بياخد العنصر الواحد فقط باستخدام document.getElementById ،
عشان كده شغال على الأيقونة الأولى التي واخده نفس الـ id.

جرب  استخدام document.querySelectorAll عشان ناخد كل العناصر اللي عندها نفس الـ id ،
ومهم انك تحددال array بعد العنصر لتحديد العنصر الصحيح

جرب 
 

const likeIcons = document.querySelectorAll('#like-icon');
const likeCount = document.getElementById('like-count');

likeIcons.forEach((likeIcon) => {
  likeIcon.addEventListener("click", () => {
    const newId = likeIcon.getAttribute('data-news');
    const url = `/like_news/${parseInt(newId)}/`;
    fetch(url, {
        method: 'GET',
        headers: {
            'Content-type': 'application/json'
        }
    })
    .then(response => {
        return response.json();
    })
    .then(data => {
        if(data.liked) {
            likeIcon.classList.remove('empty-heart');
        }
        else {
            likeIcon.classList.add('empty-heart');
        }
        likeCount.innerHTML = data.like_count;
    })
    .catch(error => {
        console.log(error);
    })
  });
});

انا استخدمت querySelectorAll بدلاً من getElementById عشان اجيب كل العناصر التي لديها نفس الـ id ،
و استخدمت تكرار forEach عشان احدد كل عنصر لوحده
. و اخترت likeIcon بدل like-icon في متغير newId داخل الحدث ليتم استخدام المتغير المناسب.

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...