You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于count值的条件判断:动态展示不同的h5元素

Got it, let's fix this conditional visitor text issue. Here's a clean way to implement the dynamic message based on the count value, working both on page load and after the AJAX update:

Step 1: Add a reusable helper function

First, create a function that handles updating the text based on the count and the specific text element (so it works if you have multiple visitor sections on the page):

function updateVisitorText(textElement, countValue) {
  if (countValue === 1) {
    textElement.text('person has visited');
  } else {
    textElement.text('people have visited');
  }
}

Step 2: Initialize the text on page load

We need to set the correct text when the page first loads, matching the server-rendered count:

$(document).ready(function() {
  // Loop through all count elements to initialize their text
  $('.count').each(function() {
    const initialCount = parseInt($(this).text());
    const textElement = $(this).siblings('.count-text');
    updateVisitorText(textElement, initialCount);
  });
});

Step 3: Update the text after AJAX count changes

Modify your existing AJAX callback to update the text right after adjusting the count value. We'll target the specific count-text element related to the clicked button:

$('.visit').on('click', function(event){ 
  event.preventDefault(); 
  const buttonToChange = $(this); 
  const $this = $(this); 

  $.ajax({}) 
  .done(function() { 
    const countElement = $this.siblings('.count');
    const textElement = $this.siblings('.count-text');
    let newCount;

    if(buttonToChange.hasClass('btn-visited')){
      buttonToChange.addClass('btn-not-visited').removeClass('btn-visited');
      buttonToChange.html('Visited?');
      newCount = parseInt(countElement.html()) - 1;
      countElement.html(newCount);
    } else {
      buttonToChange.addClass('btn-visited').removeClass('btn-not-visited');
      buttonToChange.html("I've Visited <i class='fas fa-check'></i>");
      newCount = parseInt(countElement.html()) + 1;
      countElement.html(newCount);
    }

    // Update the visitor text with the new count
    updateVisitorText(textElement, newCount);
  }); 
});

How this works:

  • The helper function keeps the conditional logic DRY (Don't Repeat Yourself) so we can use it both on page load and after AJAX updates.
  • By targeting sibling elements of the clicked button, we ensure only the relevant visitor text gets updated (perfect if you have multiple places on the same page).
  • We calculate the new count once and reuse it, avoiding redundant DOM reads.

内容的提问来源于stack exchange,提问作者detinu20

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:01:07