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