我在for循环中有一个for循环。第一个for循环遍历每座建筑物,第二个遍历每一个具有前提条件的建筑物(只希望显示具有前提条件的建筑物)。完成后,我将显示4座建筑物,每座建筑物都有自己的名称,ID,描述和构建选项。我的问题是,当我单击构建时,会弹出我的模态,但无论我单击哪个构建构建按钮,都只会显示第一个建筑物的内容。我要在模式中显示的是建筑物名称,所需资源和建筑物确认信息,但我只能从第一座建筑物中获取数据
<div class="buildingsWithPrerequisite">
<% for(var i = 0; i < newBuildingInfo.length; i++){ %>
<% for(var j = 0; j < buildings_with_pre.length; j++){ %>
<% if(newBuildingInfo[i][0] == buildings_with_pre[j][0]){ %>
<li>
<%= newBuildingInfo[j][0] %> <br> <!-- Building Id -->
<%= newBuildingInfo[j][1] %> <br> <!-- Building Name -->
<%= newBuildingInfo[j][2] %> <br> <!-- Building Description -->
<!-- If requiremnt is met, color green, if not then red-->
<% if(buildings_with_pre[j][3] == false) { %>
<p style="color:red;">Requirement:
<%= buildings_with_pre[j][1] %>
Level <%= buildings_with_pre[j][2] %> </p>
<button class="btn btn-secondary" disabled>Build</button>
<% } else {%>
<p style="color:green;">Requirement:
<%= buildings_with_pre[j][1] %>
Level <%= buildings_with_pre[j][2] %> </p>
<!-- Build Button with Popup-->
<form method="POST" action="/building-construct">
<button type = "button" id="buildButton" class = "btn btn-success" data-toggle="modal" data-target="#constructWithPreBuilding" onclick="myfunc()"> Build </button>
<div class="modal fade" id="constructWithPreBuilding" role="dialog" aria-labelledby= "exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel"> <%= newBuildingInfo[j][1] %> </h5> <!-- Building Name-->
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<%= newBuildingInfo[j][2] %> <br> <!-- Building Description -->
Time: <br>
Cost: <br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal"><!--Close--> <%= newBuildingInfo[j][0] %></button>
<% if(can_build_with_pre[j] == true){ %>
<input type="hidden" name="buildingId" value = <%= buildings_with_pre[j][0] %>>
<input type="hidden" name="locationId" value = <%= location %>>
<input type = "Submit" class = "btn btn-success constructsBuilding" value = "Construct" >
<% } else { %>
<button type = "button" class="btn btn-secondary" disabled> Not Enough Resources</button>
<% } %>
</div>
</div>
</div>
</div>
</form>
<% } %>
</li>
<% } %>
<% } %>
<% } %>
</div>
答案 0 :(得分:0)
从我的看到,Ids存在问题。在每个for循环中,您的ejs代码都会为每个建筑物生成一个模式。结果,您有许多包含不同数据但具有相同ID constructWithPreBuilding
的模态。此外,这些模态由具有相同id="buildButton"
和data-target="#constructWithPreBuilding"
的按钮触发。
每个模式和按钮应具有唯一的ID。
我首先要更改的是为每个模式指定一个ID,例如“建筑ID”
<div class="modal fade" id="<%= newBuildingInfo[j][0] %>" role="dialog" aria-labelledby= "exampleModalLabel">
并在按钮上进行相同的更改
<button type = "button" id="bB<%= newBuildingInfo[j][0] %>" class = "btn btn-success" data-toggle="modal" data-target="#<%= newBuildingInfo[j][0] %>" onclick="myfunc()"> Build </button>
希望它对您有帮助,或者给您类似的想法。