JavaScript字符串转整数异常:替换数字可运行,求助排查问题
Let me walk through the problems in your code and show you how to get it working properly:
1. The parseInt Syntax Error
You wrapped the entire jQuery call in quotes inside parseInt, which means you're trying to parse the string "$(this).attr('id')" instead of the actual value of the row's ID. That's why your conversion to integer isn't working. You need to remove those quotes so jQuery can execute the method and return the ID value.
2. The Core Problem: Frontend vs. Backend Execution Order
The big issue here is how you're trying to use {{ usage[x] }}. Template tags like this are processed by your backend before the page even loads in the browser. But your x variable is a frontend JavaScript variable that only gets set when the user clicks a row—long after the backend has finished rendering the page. The backend has no idea what x is at the time it renders the template, so this line will never work as written.
How to Fix It
You need to pass the entire usage dataset to your frontend as a JavaScript variable first, then access it using your frontend x value. Here's the step-by-step fix:
First, inject your backend usage data into a frontend JS variable (this example uses Jinja2 syntax, adjust if you're using a different templating engine):
<script> // Convert backend data to a JS array accessible in the browser const usageData = {{ usage|tojson }}; </script>
Then fix your click event code:
$(document).ready(function() { $('#iptable tr').click(function (event) { // Correctly get and parse the row's ID to an integer var x = parseInt($(this).attr('id'), 10); // Always specify base 10 for parseInt // Add a check to avoid invalid indices or NaN values if (!isNaN(x) && x >= 0 && x < usageData.length) { alert(usageData[x]); } else { alert("Invalid row ID or index out of bounds"); } }); });
Why This Works
- We're now parsing the actual ID value of the clicked row instead of a string of code.
- By converting the backend
usagedata to a frontend JS array, we can dynamically access its elements using thexvariable that's set when the user clicks a row—this happens entirely in the browser, after the page has loaded.
内容的提问来源于stack exchange,提问作者Issa Daniel

