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

如何实现传入Div类名的通用jQuery清空元素函数

Hey there! Let's fix up that clear function for your divs—your current code has a few small issues that are keeping it from working as expected. Let's break it down and build the right solution.

First, let's spot the problems in your existing code

  • You're using a fixed selector .cntrl in your function instead of the cntrl parameter you pass in. This means the function will always target elements with the cntrl class, no matter what class name you send it.
  • ajaxForm is a method from the jQuery Form plugin, which is meant for handling AJAX form submissions—not clearing div content. Plus, this.reset() only works on <form> elements, not divs, so that logic doesn't apply here.
  • In your button's onclick handler, you're passing adds without quotes. JavaScript will treat this as an undefined variable instead of the class name string you intend.

Here's the corrected universal clear function

We'll use jQuery's .empty() method (the standard way to remove all child elements and content from a target element) and make sure we use the passed-in class name correctly:

function ClearCntrl(cntrlClass) {
  // Target all elements with the specified class name and clear their content
  $('.' + cntrlClass).empty();
}

If your div contains form elements and you need to reset them too

If the div has form inputs that need their values reset (not just removed), extend the function like this:

function ClearCntrl(cntrlClass) {
  const $targetDivs = $('.' + cntrlClass);
  
  // Clear all content inside the divs
  $targetDivs.empty();
  
  // Reset any forms inside the divs (if needed)
  $targetDivs.find('form').each(function() {
    this.reset();
  });
}

Fix the button's onclick handler

Make sure to pass the class name as a quoted string:

<input type="submit" name="name-submit" value="submit" id="name-submit" class="btn btn-info" onclick="ClearCntrl('adds')">

Bonus: Better practice—use jQuery event binding instead of inline onclick

For cleaner, more maintainable code, separate your JavaScript from your HTML by binding the click event with jQuery:

<input type="submit" name="name-submit" value="submit" id="name-submit" class="btn btn-info">
// Wait for the DOM to load before binding events
$(document).ready(function() {
  $('#name-submit').click(function(e) {
    e.preventDefault(); // Prevent the default form submit behavior (if needed)
    ClearCntrl('adds');
  });
});

内容的提问来源于stack exchange,提问作者Manoj Patil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:47:42