gpt4 book ai didi

javascript - 将不同的元素传递给具有相同 ID 的 Javascript 函数

转载 作者:行者123 更新时间:2023-11-30 18:07:07 24 4
gpt4 key购买 nike

我有一个 jsp 文件,我在其中以表格的形式从数据库中检索数据。我的jsp如下:

<%
ResultSet rs1 = stmt.executeQuery("select * from book where category='Fiction'");
%>

<h1><font size="3">
<form name="f1" id="f1" method="post">
<table border="1">
<tr>
<th>Name of the Book</th>
<th>Author</th>
<th>ISBN</th>
<th>Price</th>
<th>Publication</th>
<th>Description</th>
</tr>
<%
while(rs1.next())
{
%>
<tr>
<td id="bname"><%= rs1.getString(1) %></td>
<td id="aname"><%= rs1.getString(2) %></td>
<td id="isbn"><%= rs1.getString(3) %></td>
<td id="price"><%= rs1.getString(4) %></td>
<td id="pname"><%= rs1.getString(5) %></td>
<td id="desc"><%= rs1.getString(7) %></td>
<td><input type="button" value="Add to Cart" onclick="cart()"></input></td>
</tr>
<%
}
%>

此输出将以行数表示。当我单击“添加到购物车”按钮时,它应该将单元格元素传递给 javascript 函数,从而通过 JS 函数传递给 servlet。

我在这里面临的问题是,由于每个“td”的 ID 都相同,尽管我单击了他表的第二行,但只有第一行的元素被传递到 javascript 函数中。

这是我的 javascript 函数:

function cart()
{
var bname = window.document.getElementById("bname").textContent;
var isbn = window.document.getElementById("isbn").textContent;
var price = window.document.getElementById("price").textContent;
alert(bname);
alert(isbn);
alert(price);
}

上面的“警报”仅显示第一行的值,尽管我单击了第二行中的按钮。

我在网上尝试了很多替代方案,但都无法解决问题。

最佳答案

  1. 从不在一个页面中出现两次相同的 ID
  2. 将唯一键(最好是行的 ID)连接到 TD 的 ID。在您的代码中使用该计算出的 ID。应该很简单

代码:

//assuming 0 is the ID index in the row  
<td id="bname<%= rs1.getString(0) %>"><%= rs1.getString(1) %></td>

<td><input type="button" value="Add to Cart"
onclick="cart(<%= rs1.getString(0) %>)"></input></td>

...
...
...

function cart(id) {
var bname = window.document.getElementById("bname"+id).textContent;
var isbn = window.document.getElementById("isbn"+id).textContent;
var price = window.document.getElementById("price"+id).textContent;

alert(bname);
alert(isbn);
alert(price);
}

关于javascript - 将不同的元素传递给具有相同 ID 的 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15550450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com