不使用jQuery实现点击父元素为子元素添加类
Replace jQuery with Vanilla JavaScript for WordPress Admin Click Functionality
Got it, let's fix this by swapping out the jQuery code with vanilla JavaScript—this will work reliably in the WordPress admin, including on mobile devices. Here's how to do it:
Final Working Code
CSS (keep your existing styles)
.show-controls { color: red; }
HTML (no changes needed)
<div class="wpb_vc_column"> <div class="vc_controls">SomeThing</div> </div>
Vanilla JavaScript (replace your jQuery code with this)
// Wrap in an IIFE to avoid polluting the global scope (WordPress-friendly) (function() { // Wait for the DOM to be fully loaded before binding events document.addEventListener('DOMContentLoaded', function() { // Handle both click (desktop) and touchstart (mobile) events function handleColumnInteraction(e) { // Find the closest parent .wpb_vc_column element from the clicked/touched target const column = e.target.closest('.wpb_vc_column'); if (column) { // Prevent default behavior (matches your original jQuery code) e.preventDefault(); // Locate the child .vc_controls element const controls = column.querySelector('.vc_controls'); // Add the class if the controls element exists if (controls) { controls.classList.add('show-controls'); } } } // Bind the handler to click and touch events document.addEventListener('click', handleColumnInteraction); document.addEventListener('touchstart', handleColumnInteraction); }); })();
Key Details & Why This Works
- Event Delegation: By binding the event to the
documentinstead of individual.wpb_vc_columnelements, we ensure the code works even if new columns are dynamically added to the WordPress admin (common in page builders like Visual Composer). - Mobile Support: Adding
touchstartalongsideclickensures the functionality triggers smoothly on mobile devices without lag. - WordPress-Friendly: The IIFE (Immediately Invoked Function Expression) prevents variable conflicts with other scripts in the WordPress admin.
- DOM Safety: Using
DOMContentLoadedguarantees we don't try to bind events before the page's elements are fully rendered.
If you need to toggle the class instead of just adding it (e.g., click again to remove), replace classList.add with classList.toggle.
内容的提问来源于stack exchange,提问作者Anup Gupta
相关产品推荐
相关产品推荐

