Maison  >  Questions et réponses  >  le corps du texte

Afficher les compteurs d'inventaire à plusieurs endroits sur la même page

Ce script fonctionne très bien comme compte à rebours de stock, mais je ne peux pas l'afficher à plus d'un endroit sur la même page.

Par exemple, il y a 4 ou 5 produits/plans sur la même page, chaque produit affiche une quantité de stock différente, et la quantité change à des moments différents. Affiché sur 1 seul produit.

<span class="qty" id="qty"></span>

<script>
    const setQty = (qty) => {
        qtySpan.innerHTML = qty;

        if (qty == 0) return;

        let parts = Math.floor((Math.random() * 3) + 1);
        if (parts > qty) parts = qty;

        const msec =  Math.floor(((Math.random() * 15) + 15) * 1000);
        qty -= parts;

        // Save the updated quantity in localStorage
        localStorage.setItem('saved_countdown', qty);

        setTimeout(() => setQty(qty), msec);
    }

    // Get the saved countdown value from localStorage, or use default value of 57 if not found
    const defaultQty = localStorage.getItem('saved_countdown') ?? 57;
    
    const qtySpan = document.getElementById('qty');

    // Set the initial value of the quantity
    setQty(defaultQty);
</script>

J'ai copié le script 4x et changé l'ID "qté" en qté1, qté2, qté3 et qté4 mais ça ne marche pas, il n'apparaît que dans 1 produit... :/

Quelqu'un ici peut-il m'aider ? Merci!

P粉038161873P粉038161873181 Il y a quelques jours2539

répondre à tous(2)je répondrai

  • P粉536532781

    P粉5365327812024-04-03 12:53:43

    J'ai modifié la fonctionnalité afin que vous puissiez avoir plusieurs comptes à rebours.

    const setQty = (qtySpan, qty) => {
    qtySpan.innerHTML = qty;
    
    if (qty == 0) return;
    
    let parts = Math.floor((Math.random() * 3) + 1);
    if (parts > qty) parts = qty;
    
    const msec = Math.floor(((Math.random() * 15) + 15) * 1000);
    qty -= parts;
    
    // Save the updated quantity in localStorage
    localStorage.setItem('saved_countdown', qty);
    
    setTimeout(() => setQty(qty), msec);
    }
    
    const defaultQty = localStorage.getItem('saved_countdown') ?? 57;
    
    let listOfQty = document.querySelectorAll('.qty');
    listOfQty.forEach((qty) =>{
        setQty(qty, defaultQty);
    
    })

    Vous envoyez simplement le numéro spécifique pour chaque compte à rebours comme deuxième paramètre.

    répondre
    0
  • P粉761718546

    P粉7617185462024-04-03 10:19:41

    J'ai modifié votre script en un élément personnalisé. Cela signifie que vous pouvez maintenant créer un élément appelé <stock-counter> .

    Cet élément a 2 attributs, quantitystorage-key.

    1. quantity est le montant à partir duquel commencer à compter.
    2. storage-key 是本地存储密钥的名称,用于存储特定计数器的最后数量。如果设置了存储键并且找到了存储值,则该值将取代 quanitity 值,除非存储值是 0.

    L'élément ressemble donc à ceci :

    40
    

    Vous pouvez placer n'importe quel nombre de ces éléments sur la page et modifier le quantitystorage-key de chaque élément.

    customElements.define('stock-counter', class extends HTMLElement {
      get quantity() {
        // Check if value has been stored.
        if (this.storageKey !== null) {
          const value = Number(localStorage.getItem(this.storageKey));
    
          // Use that value if it is a valid number and not 0.
          if (!Number.isNaN(value) && value !== 0) {
            return value;
          }
        }
    
        // Otherwise get the value from the quantity attribute.
        const value = Number(this.getAttribute('quantity'));
    
        if (Number.isNaN(value)) {
          return 0;
        }
    
        return value;
      }
    
      set quantity(value) {
        if (!isNaN(value)) {
        
          // Store the new value if it's possible.
          if (this.storageKey !== null) {
            localStorage.setItem(this.storageKey, value);
          }
    
          // Set the new attribute value.
          this.setAttribute('quantity', value);
        }
      }
    
      get storageKey() {
        return this.getAttribute('storage-key');
      }
    
      connectedCallback() {
        this.count();
      }
    
      count = () => {
        const qty = this.quantity;
        this.textContent = qty;
    
        if (qty === 0) {
          return;
        }
    
        let parts = Math.floor((Math.random() * 3) + 1);
    
        if (parts > qty) {
          parts = qty;
        }
    
        this.quantity -= parts;
    
        const msec = Math.floor(((Math.random() * 15) + 15) * 1000);
        setTimeout(this.count, msec);
      };
    });
    40
    50
    80

    répondre
    0
  • Annulerrépondre