JSP和jQuery - 将onclick函数添加到可变数量的元素中

时间:2016-03-31 13:12:56

标签: javascript jquery jsp

给出以下jsp

<c:forEach items="${cartdata.cart }" var="t" varStatus="i">
    <div class="horizontal boxShadow section">
        <h2 class="horizontal">${ t.hotel.name }</h2>
        <p>Start: ${ t.stay.start }  End: ${ t.stay.end }</p>
        <p class="horizontal">Number of rooms: <input type="text" disabled="true" value="${t.hotel.numRooms }" id="res${i.index }" />   <input type="button" value="Edit" id="resbut${i.index }" /></p>
        <p class="horizontal">Room Price:$ ${t.hotel.roomPrice } Cost:$ ${t.cost } </p>
        <div id="roomStatus${i.index}"></div>
    </div>
    <br />
</c:forEach>

我正在尝试为每个按钮添加功能,以便我可以编辑每个ID = res+${i.index}文本输入中的值。

JS:

$(document).ready(function() {
    var length = ${cartdata.cart.size()};
    for (i = 0; i<length; i++){
        $('#resbut' + i).click(function() {
            $("res" + i).prop("disabled", false);
        });
    }
});

2 个答案:

答案 0 :(得分:0)

忘了给他们ids。它使事情变得过于复杂。改为给他们上课。通过遍历DOM找到相关项目。

有些事情:

{
   "_id": ObjectId("56fd1ad11c8cb633208b4569"),
   "message": "I deal in Cosmetic Products.",
   "type": "groupchat",
   "from_id": "56b07a5a083f119a0b8b4569",
   "chat_id"▼: "56fa3f5f1c8cb667138b4567",
   "updated_at": ISODate("2016-03-31T12:40:49.807Z"),
   "created_at": ISODate("2016-03-31T12:40:49.807Z") 
}

{
   "_id": ObjectId("56fd1ab41c8cb6f1298b456a"),
   "message": "What business do you deal in.",
   "type": "groupchat",
   "from_id": "56b087d4083f11ea218b4567",
   "chat_id": "56fa3f5f1c8cb667138b4567",
   "updated_at": ISODate("2016-03-31T12:40:20.465Z"),
   "created_at": ISODate("2016-03-31T12:40:20.465Z") 
}

答案 1 :(得分:0)

如果要启用/禁用与按钮对应的输入,可以尝试:

   $(':button').click(function(){
        var $parent=$(this).parent();
        $parent.find(':text').attr('disabled',false);
        $('p').not($parent).find(':text').attr('disabled',true);
    });