簡體   English   中英

如何使用Javascript獲取選定的列表項?

[英]How to get a selected list item using Javascript?

我在應用程序中顯示數據庫中的內容列表。 我從數據庫中獲取記錄,並遍歷前端的for-each循環,它顯示了內容。 當我嘗試單擊任何一項時,它僅顯示列表中的第一項。 下面是我的代碼。 我該如何克服這個問題?

function userselection()
        {
            var selecteduser1=document.getElementById("lbl_user").innerHTML;
            document.writeln(selecteduser1);
        }

<div style="border: 2px solid activeborder;width:300px;height: 400px;border-radius: 5px;">
                    <ul id="userlist" style="text-align: left;">
                        <c:forEach items="${list_onlineusers}" var="userslist">
                            <li  id="li_user" style="list-style-image: url(images/online.png);cursor: pointer;height: 25px;margin-left: 0;margin-right: 10%;margin-top: 0.5em;margin-bottom: 7%;" value="${userslist}">
                                <label onmousedown="userselection()" id="lbl_user" style="font-family:Trebuchet MS,Times,serif;color: black;font-size: 16px;cursor: pointer;">
                                    ${userslist}
                                </label>
                            </li>
                        </c:forEach>
                    </ul>
                </div>

ID的定義和用法

id屬性指定HTML元素的唯一ID(該值在HTML文檔中必須是唯一的)。id屬性最常用於指向樣式表中的樣式,並由JavaScript(通過HTML DOM)進行操作具有特定ID的元素。

您對列表中的所有項目使用相同的ID。 您只需稍微更改<c:forEach>循環,即可將循環計數添加到id中。 因此,每個商品都有唯一的ID。 請像下面那樣更改您的代碼

<c:forEach items="${list_onlineusers}" var="userslist" varStatus="count">
   <li  id="li_user${count.index}" value="${userslist}">
        <label onmousedown="userselection()" id="lbl_user${count.index}">
          ${userslist}
         </label>
   </li>
</c:forEach>

上面的更改將為每個項目設置唯一的ID。 現在,您可以將在注冊事件偵聽器時單擊的項目的唯一ID傳遞給文檔,然后執行所需的任何操作。 首先,您需要確保文檔中的每個元素都有唯一的ID。

注意:我已經從您的HTML中刪除了內聯CSS樣式屬性,以提高可讀性

您正在使用ID“ lbl_user”進行所有選擇; 由於所有項目都共享相同的ID,因此

var selecteduser1=document.getElementById("lbl_user").innerHTML;

被調用時,它僅獲取第一個可用的ID。 嘗試為每個項目分配唯一的ID。

或者,在函數中,只需執行以下操作:

function userselection(){
     var selecteduser1=this.innerHTML;
     document.writeln(selecteduser1);
}

您的循環執行不正確,因為您的循環會在視圖上創建id =“ li_user”和id =“ lbl_user”的多個ID,但並非唯一。 首先修復該問題。

您好,您可以嘗試不使用Java腳本。

  List<String> list = (List<String>) s;
 {
    %>
<tr>
<td>MobileCode</td>
<td>Company</td>
<td>Camera</td>

<%
for (String p : list) {
%>
<tr>
<td><%=p.getMn()%></td>
<td><%=p.getCmnm()%></td>
<td><%=p.getCmr()%></td>

<td><a href="xyz`enter code here.jsp?mn=<%=p.getMn()%>"
onClick="return confirm('Are you sure for Delete')">Delete</a></td>
</tr>
<%
}
}
}
enter code here

}
%>
</table>

像這樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM