如何为每个复选框分配唯一ID?

时间:2017-03-22 06:21:51

标签: javascript xml xslt checkbox

我正在尝试检查复选框是否已选中。但是,我面临的问题是我使用循环(xsl:for-each)根据XML自动生成复选框。由于我自动生成它们,因此我无法为每个复选框设置不同的ID,这使我无法更新特定复选框的属性以获取已检查的指示。另外,每当我选中一个复选框(无论是第一个还是最后一个)时,第一个复选框将是更新的复选框。有人可以给我一个建议吗?或者至少让我朝着正确的方向前进?提前谢谢。

这是我的XSLT代码:

  <xsl:if test="$type='MultiList'">
          <xsl:for-each select="./options/item">
            <xsl:element name="input">
              <xsl:attribute name="type">checkbox</xsl:attribute>
              <xsl:attribute name="id">hey</xsl:attribute>
              <xsl:attribute name="onchange">hii()</xsl:attribute>
              <xsl:attribute name="score">
                <xsl:value-of select="@score"/>
              </xsl:attribute>
              <xsl:attribute name="value">
                <xsl:value-of select="item"/>
              </xsl:attribute>

            </xsl:element>
            <label>
              <xsl:value-of select="."/>
            </label>
          </xsl:for-each>
        </xsl:if>

这是javascript:

<script>


    function hii(){

    var a = document.getElementById('hey');
    a.setAttribute("score","1");
    }
  </script>

1 个答案:

答案 0 :(得分:0)

每个复选框都不需要ID。

更改函数定义以接受参数:

function hii(checkbox) {
    checkbox.setAttribute("score", (checkbox.checked ? 1 : 0));
}

然后将this传递给hii()

<xsl:attribute name="onchange">hii(this)</xsl:attribute>

或者删除onclick属性并使用附加到复选框的父元素的单击处理程序。

示例:

var parent = document.querySelector("div");
parent.addEventListener("click", function(e) {
  if (e.target.nodeName !== "INPUT") {
    return;
  }
  
  e.target.setAttribute("score", e.target.checked ? 1 : 0);
});
<div>
    <input type="checkbox" name="cb1" />
    <input type="checkbox" name="cb2" />
    <input type="checkbox" name="cb3" />
</div>

相关问题