如何在DOM变更后获取元素初始的Id、Value或文本内容?
Great question! The issue here is that attr('id') pulls the current value of the element's id attribute from the DOM—so when you update that attribute later, it returns the new value instead of the original. To fix this, we need to store the original ID in a place that doesn't get affected by DOM attribute changes. Here are two reliable approaches:
1. Use HTML5 Data Attributes (Recommended for Static Initialization)
If you control the initial HTML, add a custom data-* attribute to store the original ID right from the start. This attribute won't be touched when you modify the element's id later:
<!-- Initial HTML --> <input id="1" data-original-id="1"> <button class="edit_btn">Edit</button>
Then, in your click handler, fetch this static data attribute instead of the dynamic id:
$(document).on('click','.edit_btn:eq(0)',function(){ var itm_id = $(this).siblings('input').data('original-id'); alert(itm_id); // Will always return "1", even if the id is updated to "34" });
2. Cache the Original ID with jQuery's Data Storage (For Existing/Generated Elements)
If you can't modify the initial HTML, cache the original ID in jQuery's internal data store when the page loads (or when dynamic elements are added to the DOM). This stores the value separately from the DOM attributes:
Step 1: Cache the original ID on page load
$(document).ready(function() { // Target the input and store its initial ID $('.edit_btn:eq(0)').siblings('input').each(function() { $(this).data('originalId', $(this).attr('id')); }); });
Step 2: Retrieve the cached ID in your click handler
$(document).on('click','.edit_btn:eq(0)',function(){ var itm_id = $(this).siblings('input').data('originalId'); alert(itm_id); // Returns the original ID, not the updated one });
Important Note for Dynamic Elements
If the input/button are added to the DOM after page load (e.g., via AJAX), run the caching code right after the elements are inserted, not in $(document).ready(). For example:
// After adding dynamic elements to the DOM var newInput = $('<input id="1" class="dynamic-input">'); var newBtn = $('<button class="edit_btn">Edit</button>'); $('#container').append(newInput, newBtn); // Cache the original ID immediately newInput.data('originalId', newInput.attr('id'));
Why This Works
attr('id')reads directly from the DOM's current attribute value, which changes when you update the element's ID.- jQuery's
data()method stores values in an internal cache tied to the element, not in the DOM itself. This means the original ID stays safe even if you modify the element'sidattribute later.
内容的提问来源于stack exchange,提问作者Sang Nguyen

