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

如何实现针对人员卡片div的搜索筛选,使匹配的完整卡片(含图片与姓名)显示

Got it, let's fix this! The problem right now is your code is only showing/hiding the individual name <p> tags instead of the entire person card. Let's walk through the fixes, starting with a critical HTML issue you might not have noticed.

Step 1: Fix Duplicate IDs (Critical!)

You’ve got multiple cards using id="columndiv"—but HTML rules require IDs to be unique. This will break JavaScript selectors and cause unexpected behavior. Swap that ID out for a class instead:

<!-- Old -->
<div class="col-3" id="columndiv">
<!-- New -->
<div class="col-3 columndiv">

Update this for all 40 of your person cards.

Step 2: Rewrite the JavaScript to Target Whole Cards

Instead of looping through every <p> tag, we’ll grab each full card, check the name inside it, and toggle the card’s visibility. Here’s the updated function:

function myFunction() {
  const input = document.getElementById('myInput');
  const filter = input.value.toUpperCase();
  // Get every person card using our new class
  const allCards = document.querySelectorAll('.columndiv');

  allCards.forEach(card => {
    // Grab the first <p> tag in the card (this is the person's name)
    const nameText = card.querySelector('.texttrial p:first-child').textContent.toUpperCase();
    
    // Show the card if it matches the filter, hide it if not
    card.style.display = nameText.includes(filter) ? 'block' : 'none';
  });
}

Key Changes Explained

  • Target the full card: We use querySelectorAll('.columndiv') to grab every person card instead of individual text elements.
  • Check the name directly: For each card, we pull the name text from the first <p> inside the .texttrial container.
  • Toggle the entire card: We adjust the card’s display property, so the whole image + name + role block shows/hides as a single unit.

Bonus: Improve Empty Search UX

If you want all cards to reappear when the user clears the search box, add this quick check at the top of the function:

function myFunction() {
  const input = document.getElementById('myInput');
  const filter = input.value.toUpperCase();
  const allCards = document.querySelectorAll('.columndiv');

  // Show all cards if input is empty
  if (!filter) {
    allCards.forEach(card => card.style.display = 'block');
    return;
  }

  allCards.forEach(card => {
    const nameText = card.querySelector('.texttrial p:first-child').textContent.toUpperCase();
    card.style.display = nameText.includes(filter) ? 'block' : 'none';
  });
}

That’s it—now when you search a name, the entire matching card will display, and non-matching cards will be hidden.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 00:28:11