如何在JavaScript中用变量作为id属性?Jaggery代码取值失败求助
Hey there! Let's break down why you're struggling to get the value from your dynamically generated input field, and how to fix it step by step.
First, Verify the Generated HTML
Before diving into code fixes, let's confirm your Jaggery loop is actually generating the correct id attributes. Right-click your page, select "View Page Source", and look for the input elements. You should see something like:
<input type="text" id="attribute_0"> <input type="text" id="attribute_1"> <!-- More inputs based on applicationAttributes length -->
If attribute_1 doesn't show up here, that means your applicationAttributes array has fewer than 2 elements (since the loop starts at i=0). Double-check the array's length first!
Common Issues & Fixes
1. Your jQuery Code Runs Before the DOM is Ready
If you're trying to fetch the value before the page finishes rendering the input elements, jQuery won't find the #attribute_1 selector. To fix this, wrap your code in $(document).ready() to ensure it runs only after the DOM is fully loaded:
$(document).ready(function() { // Trigger this code on an event (like a button click) or directly here $("#get-value-btn").click(function() { var data = $("#attribute_1").val(); console.log(data); // Check the browser console (F12) for the value }); });
Alternatively, place your <script> tag at the very bottom of your page, right before the closing </body> tag—this ensures all elements are rendered before your code runs.
2. Ensure jQuery is Properly Loaded
If you see a $ is not defined error in your browser console, that means jQuery isn't loaded on your page. Add this script tag in your <head> or before your custom jQuery code:
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
3. Clean Up Your Jaggery Loop Code
Your original loop is mostly correct, but adding var to the loop variable avoids global scope pollution, and consistent spacing makes it easier to read:
<% for (var i = 0; i < applicationAttributes.length; i++) { %> <div> <label>data:</label> <div> <input type="text" id="attribute_<%= i %>"> </div> </div> <% } %>
Final Check List
- Confirm
applicationAttributes.length >= 2soattribute_1exists - Verify the generated HTML has the correct
id - Make sure jQuery is loaded and your code runs after the DOM is ready
- Check the browser console (F12) for any errors that might give clues
内容的提问来源于stack exchange,提问作者Vithursa Mahendrarajah

