如何捕获$('.input_fields_wrap')中append的h1标签id值并存入var data
Solution to Extract ID from Dynamically Added H1 Tag
Hey there! I see you're trying to pull just the ID value from that .id class H1 tag instead of grabbing all the text from the parent div. Let's adjust your code to make that happen easily.
The Fix
Instead of using .parent('div').text() which grabs everything, we'll target the specific .id H1 tag inside the parent div. Here's how to modify your click handler:
- First, get the parent div of the clicked remove button (you already have that part)
- Use
.find('.id')to locate the H1 with classidinside that div - Grab its text content, and use
.trim()to clean up any extra whitespace from the template rendering
Modified Code
Here's the updated script section with the fix:
<script> $(document).ready(function(e){ $('.input_fields_wrap') .append('{% for s in speaker %}<div class="col-md-3 col-sm-6 text-center"><img id="button"src="{{s.ProfileImg.url}}"alt=""><h1 class="id"> {{s.id}} </h1><h1 name="name" class="name"> {{s.Name}} </h1> <h4>{{s.Technical_Area}} | {{s.Brief_Bio}} </h4><p>{{s.Email}} | {{s.Phone}} | {{s.Social_Media}}</p><button type="button" class="remove_field">Remove</button> <button type="button" class="edit_field">Edit</button></div>{% endfor%}'); }); $('.input_fields_wrap').on("click",".remove_field", function(e){ e.preventDefault(); const parentDiv = $(this).parent('div'); // Extract the ID value from the .id H1 tag const data = parentDiv.find('.id').text().trim(); console.log(data); // This will now log just the ID, no extra text parentDiv.detach(); // Moved detach here to ensure we access the element before removing it }); </script>
Key Notes
- I moved the
.detach()call after extracting the ID to make sure we don't remove the element before accessing its child content (safer practice, even if it might work the other way around) .trim()is critical here because your template has spaces around{{s.id}}— without it, you'd get a string with leading/trailing whitespace- Using
.find('.id')is reliable because it targets exactly the element you need, even if other elements are added to the div later
内容的提问来源于stack exchange,提问作者K.Kanavi
相关产品推荐
相关产品推荐

