2017-03-22 61 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

相關問題