点击匹配data-modal的a标签为Modal添加open类失效,求排查原因
Your code has two key issues that are preventing it from working as expected, plus a minor improvement to enhance user experience:
1. Incorrect Variable Interpolation in Selector
You tried using template literal syntax ${addressValue} inside single quotes, but this doesn’t work in regular string contexts. The browser treats ${addressValue} as literal text instead of inserting the actual value of your variable. This means your code was looking for an element with data-modal="${addressValue}" (exact string), not the value you extracted from the href.
2. Wrong Selection Method
The .find() method searches for child elements inside the .modal container, but your data-modal attribute is applied directly to the .modal element itself. You don’t need to "find" inside it—you need to target the .modal element that has the matching data-modal value.
3. Missing Default Anchor Behavior Prevention
Clicking your <a> tag will trigger its default action (jumping to the element with ID matching the href), which is likely not what you want for a modal trigger. Adding e.preventDefault() stops this unwanted jump.
Corrected jQuery Code
$('.infoBox').click(function(e) { // Prevent the anchor from jumping to the top of the page e.preventDefault(); // Extract the modal ID from the href (remove the #) const addressValue = $(this).attr("href").replace('#', ''); // Target the modal with matching data-modal attribute and add the "open" class $(`.modal[data-modal="${addressValue}"]`).addClass('open'); });
Breakdown of the Fixes:
e.preventDefault(): Stops the anchor’s default navigation behavior.- Template Literals with Backticks: Using backticks
`around the selector lets the browser correctly interpolate theaddressValuevariable into the attribute selector. - Direct Attribute Selection:
.modal[data-modal="${addressValue}"]targets the exact modal element that matches the href value, no need for.find().
This approach will work perfectly even with repeated HTML structures, as it dynamically matches each trigger to its corresponding modal based on the href and data-modal values.
内容的提问来源于stack exchange,提问作者KSPR

