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

JQUERY实现点击按钮判断元素data-type值并弹窗的问题

Solution for Showing data-type on Button Click

Hey there! Let's get this sorted out for you. The main issue with your current code is that you're trying to find elements globally instead of targeting the specific <li> that contains the clicked button. Here's how to fix it:

Step 1: Target the Correct Parent Element

When a button is clicked, we need to reference its parent <li> (since that's where the data-type attribute lives). We can use $(this).closest('li') to get that parent element easily—$(this) refers to the clicked button, and closest() finds the nearest ancestor matching the selector.

Step 2: Check or Retrieve the data-type Value

Once we have the parent <li>, we can either:

  • Directly get its data-type value and show it in an alert, or
  • Check if it matches a specific value (like 'm' or 't') and show a custom message.

Full Working Code

HTML (unchanged)

<ul id="threads"> 
  <li data-href='q' data-type='m'>abc <button>Click</button></li> 
  <li data-href='q' data-type='t'>mnp <button>Click</button></li> 
  <li data-href='r' data-type='t'>rst <button>Click</button></li> 
</ul>

jQuery (fixed version)

Option 1: Show the exact data-type value directly

$(document).on("click","button",function(){
  // Get the parent li of the clicked button
  const parentLi = $(this).closest('li');
  // Retrieve the data-type value
  const type = parentLi.data('type');
  // Show it in an alert
  alert(`This is ${type} type`);
});

Option 2: Check for specific data-type values and show custom alerts

$(document).on("click","button",function(){
  const parentLi = $(this).closest('li');
  const type = parentLi.data('type');

  if (type === 'm') {
    alert("this is m type");
  } else if (type === 't') {
    alert("this is t type");
  }
});

Key Notes

  • data('type') is jQuery's method to access data-* attributes cleanly (you could also use attr('data-type'), but data() is preferred as it handles type conversion and caching).
  • closest('li') is better than parent() here because it works even if there's extra nesting inside the <li> (though in your case, parent() would also work—closest() is more robust).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:04:59