You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

在JavaScript中拼接含变量的HTML字符串遇语法错误求助

Why You're Seeing These Errors & How to Fix Them

The core issue here is that you're trying to mix client-side JavaScript-generated HTML with a runat="server" attribute, which is processed by ASP.NET on the server before your JavaScript ever runs. ASP.NET tries to parse all runat="server" tags during page rendering, but since your id value is dynamically generated in JavaScript (not known at server-render time), it can't resolve the server tag correctly—hence the "server tag is not well formed" error.

Let's break down the fixes based on whether you actually need server-side access to this <tbody> element:

Fix 1: Remove runat="server" (If You Don't Need Server-Side Access)

If you don't need to interact with this <tbody> from your server-side code (like C#/VB.NET), simply remove the runat="server" attribute. This eliminates the ASP.NET parsing conflict entirely.

Modified code:

var HTMLStr, newtbl = tbl + "Table";
HTMLStr = '<tbody id="' + newtbl + '" class="prodTbl"><tr>';

Just make sure newtbl contains a valid HTML ID (no spaces, special characters other than -, _, :, or .). If tbl might have invalid characters, sanitize it first:

// Sanitize the ID to remove invalid characters
var sanitizedTbl = tbl.replace(/[^a-zA-Z0-9\-_:.]/g, '');
var newtbl = sanitizedTbl + "Table";
HTMLStr = '<tbody id="' + newtbl + '" class="prodTbl"><tr>';

Fix 2: Generate the Element Server-Side (If You Need Server-Side Access)

If you do need to access this <tbody> from server-side code, you should create it in your code-behind instead of client-side JavaScript. This lets ASP.NET properly handle the runat="server" tag and dynamic ID.

Example in C# (code-behind):

// Assuming "tbl" is a server-side variable (adjust as needed)
string newtbl = tbl + "Table";
HtmlGenericControl tbody = new HtmlGenericControl("tbody");
tbody.ID = newtbl;
tbody.Attributes.Add("class", "prodTbl");
tbody.Runat = "server";

// Add a <tr> to the tbody (example)
HtmlGenericControl tr = new HtmlGenericControl("tr");
tbody.Controls.Add(tr);

// Add the tbody to your table (replace "yourTableID" with your actual table's server ID)
yourTableID.Controls.Add(tbody);

This way, ASP.NET generates the correct server-side control with the dynamic ID, and you won't get parsing errors.

Why the "Is not a valid identifier" Error Happens

This usually means newtbl contains characters that aren't allowed in an HTML ID or an ASP.NET server control ID. Server control IDs have stricter rules (no spaces, special characters like @, #, etc.). Sanitizing the ID as shown in Fix 1 will resolve this.

内容的提问来源于stack exchange,提问作者Edward H

火山引擎 最新活动