JQUERY实现点击按钮判断元素data-type值并弹窗的问题
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-typevalue 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 accessdata-*attributes cleanly (you could also useattr('data-type'), butdata()is preferred as it handles type conversion and caching).closest('li')is better thanparent()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

