2017-03-22 50 views
0

我正在检查是否勾选了复选框。但是,我面临的问题是我使用循环(xsl:for-each)根据XML自动生成复选框。由于我自动生成它们,我不能为每个复选框设置不同的ID,这使我无法更新特定复选框的属性,以表明它已被检查。另外,无论何时我选中复选框(无论是第一个还是最后一个),第一个复选框都将被更新。有人可以给我一个建议吗?或者至少让我在一个正确的方向?提前致谢。如何为每个复选框分配唯一的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> 

回答

0

你并不需要为每个复选框的ID。

变化的函数定义为接受一个参数:

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

再经过thishii()

<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>

+0

哇,不知道你能做到这一点到现在为止!可能是因为我刚开始学习这种语言,这就是为什么!非常感谢! – Nicholas

+0

呃,单选按钮怎么样?我试图在单选按钮上复制这种方法,但现在即使未检查,值仍然为1。你如何解决这个问题? – Nicholas

+0

我不太清楚你在说什么......也许这是值得一个单独的问题:) – Andreas

相关问题