我正在与一些让我拔头发的东西搏斗。我在此站点上找到的其他解决方案使我接近了答案,但我一直遇到绊脚石。我正在使用 ASP.Net、C# 和 JS 开发电子商务门户。我目前正在通过使用转发器显示来自 DataTable(它本身是从 SQL 查询中提取)的产品信息来填充“产品”部分。
我的 aspx 脚本如下所示:
<div class="contentContainer">
<asp:Repeater ID="productCatalog" runat="server">
<ItemTemplate>
<div class="productContainer <%#DataBinder.Eval(Container.DataItem, "pType")%>" data-category="<%#DataBinder.Eval(Container.DataItem, "pType")%>">
<img src="<%#DataBinder.Eval(Container.DataItem, "pImage")%>" class="productImage">
<h3 class="pName"><%#DataBinder.Eval(Container.DataItem, "pName")%></h3>
<p class="pDesc"><%#DataBinder.Eval(Container.DataItem, "pDesc")%></p>
<table class="productTable">
<tr>
<td class="price"><%#MoneyFormat((decimal)DataBinder.Eval(Container.DataItem, "price"))%></td>
<td><asp:Button class="btn btn-info" ID="Button1" runat="server" Text="Add to Cart" onClientClick='AddNewItem(<%#DataBinder.Eval(Container.DataItem, "pID")%>);return false;'/></td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
和我的 JS 函数:
<script type="text/javascript">
function AddNewItem(myPID) {
PageMethods.AddToCart_Command(myPID);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Cannot process your request at the moment, please try later.');
}
}
代码隐藏:
[WebMethod]
public static void AddToCart_Command(int myPID)
{
//...stuff. Not where the problem is
}
我的问题源于 aspx 文件中的这一行,特别是 onClientClick 部分:
<asp:Button class="btn btn-info" ID="Button1" runat="server" Text="Add to Cart" onClientClick='AddNewItem(<%#DataBinder.Eval(Container.DataItem, "pID")%>);return false;'/>
“pID”是一个整数值,对应于 SQL 数据库中的键。我已经尝试将一个 int 硬编码为 AddNewItem() 方法的参数,并且该函数可以正常工作。问题源于当我尝试从转发器数据本身传递参数时。如果我在参数周围使用双引号,我会收到“服务器标记格式不正确”错误。如果我使用单引号,页面构建没有错误,但单击按钮时不会调用该函数。
请注意,点击“添加到购物车”按钮后页面不会重新加载,这一点很重要。同样重要的是,按钮不是直接硬编码的。
如何将这个参数从转发器数据传递到我的 JS 函数?
非常感谢任何帮助!
编辑:作为将 pID 作为参数传递给函数的替代方法,我尝试使用 jQuery 直接从 HTML 元素中获取 pID 作为属性。不幸的是,该方法获取了具有适当 id 的元素的第一个实例,并且只会返回它。在这种情况下,中继器生产的第一个产品。
最佳答案
我可以通过简单地更改按钮类型来解决这个问题。这是最后一行:
<button class="btn btn-info" id="Button2" onclick="AddNewItem( <%#DataBinder.Eval(Container.DataItem, "pID")%> ); return false;"/>Add to Cart</button>
我从一开始就不需要 asp 按钮;这太复杂了。我能够使用上面的方法调用 JS 方法。吻。我猜!
关于javascript - 使用动态创建的内容将参数传递给 JS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35001267/