JQuery .click()事件触发后对象重复问题求助
someObject Values on Second Click with jQuery .click() Hey there! I’ve run into this exact issue before when adding table data via jQuery clicks—let’s break down why this is happening and how to fix it.
Common Causes & Solutions
1. You’re not resetting someObject before reusing it
If someObject is declared outside your click event handler, every click will modify the same object reference, leading to leftover or duplicated properties. For example:
// ❌ Bad: Object is reused across clicks let someObject = {}; $('.add-btn').click(function() { someObject.name = $('#name').val(); someObject.email = $('#email').val(); // On second click, old values might linger or get overwritten incorrectly console.log(someObject); addToTable(someObject); });
Fix: Declare or reset someObject inside the click handler so you start fresh every time:
// ✅ Good: Fresh object on each click $('.add-btn').click(function() { let someObject = {}; // Reset to empty object someObject.name = $('#name').val(); someObject.email = $('#email').val(); console.log(someObject); addToTable(someObject); });
2. Your data source is accumulating content
If you’re pulling data from dynamic elements (like added form fields) or not clearing input values after submission, you might be collecting duplicate data into someObject. For example, if you add a new input row on each click but don’t target only the latest row, you’ll grab all previous inputs too.
Fix:
- Clear form inputs after adding data:
$('#name').val(''); $('#email').val(''); - Target only the specific element/group you need for the current click (e.g., use
$(this).closest('.form-row').find('input')to get inputs from the button’s parent row).
3. Your click event is bound multiple times
If your .click() binding code runs more than once (e.g., inside an AJAX success callback or a DOM update function), you’ll end up with multiple event handlers attached to the same button. Each click will trigger all handlers, causing someObject to be populated multiple times.
Fix:
- Use event delegation to ensure the binding only happens once:
// ✅ Event delegation prevents duplicate bindings $(document).on('click', '.add-btn', function() { let someObject = {}; // Populate and add to table... });
- Or explicitly unbind before rebinding (if delegation isn’t an option):
$('.add-btn').off('click').click(function() { // Your logic here });
Quick Troubleshooting Tip
Add a console.log('Click handler triggered!') at the start of your click function. If you see this message multiple times per click, you’ve got duplicate event bindings. If not, focus on resetting someObject or cleaning your data source.
内容的提问来源于stack exchange,提问作者Iwan Wijaya

