首页 > 解决方案 > 在 forEach 语句中区分多个输入形式

问题描述

我有一个字符串数组,长度是可变的。我需要为每个字符串创建两个按钮:购买删除。他们管理相应元素的数量。像这样: 结果。我试过这个,有效,但不清楚。

String go = request.getParameter("go");
if ((go != null)){
    String[] info = go.split(",");
    int index = Integer.parseInt(info[1]);
if (info[0].equals("+")) {
    ++quantita[index];
} else {
    --quantita[index];
}}

...

    <c:forEach var="i" begin="0" end="${length-1}" >
        <%
            int i = (int) pageContext.getAttribute("i");
            out.print(products[i] + " (" + quantita[i] +" in cart)");
        %>
        <input type=submit name="go" value="-,${i}"/>
        <input type=submit name="go" value="+,${i}"/><br>
    </c:forEach>

标签: htmljspjstl

解决方案


Use <button type="submit"> instead of <input type="submit">. This HTML element allows you to set content via children rather than via value attribute. This way you can simply use the name attribute to indicate the action and the value attribute to indicate the identifier.

<button type=submit name="decrease" value="${i}">-</button>
<button type=submit name="increase" value="${i}">+</button>
String decrease = request.getParameter("decrease");
String increase = request.getParameter("increase");

if (decrease != null) {
    --quantity[Integer.parseInt(decrease)];
}
else if (increase != null) {
    ++quantity[Integer.parseInt(increase)];
}

Is that clearer?


推荐阅读