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

不使用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 document instead of individual .wpb_vc_column elements, 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 touchstart alongside click ensures 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 DOMContentLoaded guarantees 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:53:48