简体   繁体   English

struts2迭代器:避免代码重复

[英]struts2 iterator: avoiding code duplication

I'm creating a form where the user needs to add form elements dynamically. 我正在创建一个表单,用户需要动态添加表单元素。 addEmptyItem() accomplishes this by cloning the first item in the given list, clearing its values, updating its indices, and appending it. addEmptyItem()通过克隆给定列表中的第一项,清除其值,更新其索引并附加它来实现此目的。

Of course, it requires that there is at least one list item in the list. 当然,它要求列表中至少有一个列表项。 My solution is to always display the first list item, and then iterate over the rest. 我的解决方案是始终显示第一个列表项,然后遍历其余列表项。 This is bothering me due to the code duplication. 由于代码重复,这困扰着我。 It gets worse when the list items contain a lot of fields. 当列表项包含很多字段时,情况会变得更糟。

What I want is something similar to a do-while loop. 我想要的是类似于do-while循环的东西。 Any suggestions how to solve this problem without duplicating code like I'm doing now: 关于如何解决此问题而不建议像我现在所做的那样重复代码的任何建议:

<s:submit type="button" onclick="addEmptyItem($('#owners')); return false;"
          value="%{getText('ownership.addOwner')}"/>

<ul id="owners">
  <li>
    <s:textfield name="ownership.owner[0].name"
                 label="%{getText('ownership.owner.name')}"/>
    <s:textfield name="ownership.owner[0].share"
                 label="%{getText('ownership.owner.share')}"/>
  </li>

  <s:iterator value="ownership.owner" status="i" begin="1">
    <li>
      <s:textfield name="ownership.owner[%{#i.count}].name"
                   label="%{getText('ownership.owner.name')}"/>
      <s:textfield name="ownership.owner[%{#i.count}].share"
                   label="%{getText('ownership.owner.share')}"/>
  </li>
  </s:iterator>
</ul>

You could try to move code with fields to new page file and include it with like this: 您可以尝试将带有字段的代码移动到新的页面文件中,并像这样包含它:

<ul id="owners">
  <li>
   <s:include value="fileds.jsp">
      <s:param name="index" value="0" />
   </s:include>
  </li>

  <s:iterator value="ownership.owner" status="i" begin="1">
    <li>
      <s:include value="fileds.jsp">
        <s:param name="index" value="%{#i.count}" />
      </s:include>
  </li>
  </s:iterator>
</ul>

and use index param in included file. 并在包含的文件中使用索引参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM