簡體   English   中英

我希望段落在選中復選框時通過樣式獲得線條,反之亦然

[英]I want a paragraph to get the line through style whenever a checkbox is checked and vise versa

它沒有按預期工作

我設法讓它以這種方式工作:

 <div class="noteContainer">
            <p class="title">Hello World</p>
            <p class="note">This is the hello world note!
                <i class="fa fa-pencil-square-o noteEdit" title="Edit" aria-hidden="true"></i>
                <input onclick="setLineThrough()" type="checkbox" name="done" class="cbDone">
            </p>
 </div>
let checkBoxes = document.getElementsByClassName("cbDone");
const setLineThrough = () => {
    for (let i = 0; i < checkBoxes.length; i++) {
        if (checkBoxes[i].checked) {
            checkBoxes[i].parentElement.style.textDecorationLine = "line-through";
        } else {
            checkBoxes[i].parentElement.style.textDecorationLine = "none";
        }
    }
};

這不是我想要的

但是然后line through也穿過我的icon並到達checkbox所以我決定將它們從<p>中取出並進行一些更改我期待它能夠工作因為它們非常相似但它只是添加line through但是當checkbox unchecked時,它不會刪除該line through

<div class="noteContainer">
            <p class="title">Hello World</p>
            <p class="note">This is the hello world note!</p>
            <i class="fa fa-pencil-square-o noteEdit" title="Edit" aria-hidden="true"></i>
            <input onclick="setLineThrough()" type="checkbox" name="done" class="cbDone">
      </div>
let checkBoxes = document.getElementsByClassName("cbDone");
let notePara = document.getElementsByClassName("note");
const setLineThrough = () => {
    for (let i = 0; i < checkBoxes.length; i++) {
        if (checkBoxes[i].checked) {
            notePara[i].style.textDecorationLine = "line-through";
        } else {
            notePara[i].parentElement.style.textDecorationLine = "none";
        }
    }
};

我的第二次迭代有什么問題? 我只是找不到它。 另請注意,我的代碼中有一些css ,但我認為這里不需要。

您只需從您的.parentElement中刪除一個 .parentElement 實例。

您的 JavaScript 將如下所示:

let checkBoxes = document.getElementsByClassName("cbDone");
let notePara = document.getElementsByClassName("note");
const setLineThrough = () => {
    for (let i = 0; i < checkBoxes.length; i++) {
        if (checkBoxes[i].checked) {
            notePara[i].style.textDecorationLine = "line-through";
        } else {
            notePara[i].style.textDecorationLine = "none";
        }
    }
};

暫無
暫無

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

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