如何实现传入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
.cntrlin your function instead of thecntrlparameter you pass in. This means the function will always target elements with thecntrlclass, no matter what class name you send it. ajaxFormis 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
onclickhandler, you're passingaddswithout 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
相关产品推荐
相关产品推荐

