使用jQuery移除ACF字符串中指定data-layout的li标签
Hey Andy, great question! Let's break down how to solve this properly—since you're working with ACF's frontend popup, we have two solid approaches depending on whether you're dealing with already-rendered DOM elements or a raw HTML string.
Approach 1: Manipulate the DOM (Recommended)
If the ACF popup is already loaded on the page, using jQuery (which you're already familiar with) to target and remove the specific <li> is the most reliable method. Here's how:
// Define the layout you want to remove const targetLayout = 'two_column_layout'; // Find the <a> with matching data-layout, then target its parent <li> and remove it $('.acf-fc-popup ul li a[data-layout="' + targetLayout + '"]').parent('li').remove();
Why this works:
- We use jQuery's attribute selector (
[data-layout="X"]) to precisely target the link associated with your layout. .parent('li')climbs up the DOM tree to grab the exact<li>containing that link..remove()deletes the entire<li>and all its content cleanly—no messy regex needed.
Approach 2: Modify Raw HTML String
If you're working with the raw HTML string before it's inserted into the DOM, you can use a regex to strip the unwanted <li>. Just note that regex isn't ideal for HTML, but it works for simple structures like ACF's popup:
// Your raw ACF HTML string const acfHtml = '<div class="acf-fc-popup"><ul><li><a href="#" data-layout="two_column_layout" data-min="0" data-max="0">Two Column Layout</a></li><li><a href="#" data-layout="full_width_content" data-min="" data-max="">Full Width Content</a></li></ul></div>'; const targetLayout = 'two_column_layout'; // Regex to match and remove the entire <li> for the target layout const cleanedHtml = acfHtml.replace( new RegExp(`<li>.*?data-layout="${targetLayout}".*?</li>`, 's'), '' ); console.log(cleanedHtml); // Outputs HTML without the two_column_layout <li>
Regex breakdown:
new RegExp(..., 's'): Thesflag makes.match line breaks, which handles any line spacing in the HTML..*?: Non-greedy match ensures we only capture the single<li>containing your target layout, not multiple ones.
Pro Tip
Always prefer the DOM manipulation method when possible—it's more robust, especially if ACF ever changes the popup's HTML structure slightly. Regex can break if the HTML gets more complex (like nested elements inside the <li>), but DOM methods adapt automatically.
内容的提问来源于stack exchange,提问作者Andy Holmes

