簡體   English   中英

在不使用jquery進行檢查的情況下,在多組單選按鈕的父元素上添加樣式

[英]Add style on parent element of multiple set of radio buttons when checked without using jquery

我有將jquery代碼轉換為javascript的問題。 有一組單選按鈕,就像這個示例一樣,我需要在其父元素上添加樣式。

每套單選按鈕的每個選擇都會將一種樣式添加到其父項。 我只需要使用Javascript就可以了。

這是Demo :效果應該類似於第一個鏈接。

<ul>
    <li class="check"><label for="one">1<input type="radio" id="one" name="test"/></label>     
    </li>
    <li class="check"><label for="two">2<input type="radio" id="two" name="test"/></label>
    </li>
</ul>
<ul>
    <li class="check"><label for="one">1<input type="radio" id="one" name="test2"/></label>
    </li>
    <li class="check"><label for="two">2<input type="radio" id="two" name="test2"/></label>
   </li>
</ul>
<ul>
    <li class="check"><label for="one">1<input type="radio" id="one" name="test3"/></label>
    </li>
    <li class="check"><label for="two">2<input type="radio" id="two" name="test3"/></label>
    </li>
</ul>

這段代碼無需jQuery就可以提供預期的功能:

function changeEvent(event) {
    //add highlight class
    this.parentNode.classList.add("highlight");
    try {
        //remove highlight class from previously selected radio in group
        //if already existing
        this.parentNode.parentNode.highlightDIV.classList.remove("highlight");
    } catch (ignore) {}
    //keep the highlighted div as a property of the parent div
    this.parentNode.parentNode.highlightDIV = this.parentNode;
}

//select all radio buttons
var radioList = document.querySelectorAll('input[type="radio"]');
//loop through list and add event listener
for (var i = 0; i < radioList.length; i++) {
    radioList[i].addEventListener("change", changeEvent, false);
}

它使用對parentNode引用,但是可以用算法替換它們,以在更動態的結構中動態查找所需的節點。 希望您能對此有所了解,並可以改進和修改代碼以適合您的應用程序需求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM