简体   繁体   中英

How do I modify a css element with Jquery after appended with Jquery to a div?

I am making a todo list so I am adding new input tags with checkboxes on them so I can check off a to do list item. I am having trouble modifying the css so that the text displays a line through it when it is checked. The check function works and it runs but I am unable to put a line through the specific html element.

var add = function() { 
var task = $("#taskTextBox").val(); // references the value inside #task
if(task != ""){
    inc++;
    var itemName = "item" + inc;

    var newObj = $("#list").append("<input id="+itemName+" type=checkbox class="+itemName+">"+task+"<br></br>");// makes a new <p> element
    $("#taskTextBox").val(""); // empties out #task
    var newHeight = $("#list").height() + 40;
    $("#list").css({"height": newHeight});
    addAttributes();


$("input[class=" + itemName + "]").change(function () {
    if ($(this).prop("checked")) {

    $("input[class=" + itemName + "]").css({'text-decoration': 'line-through'});

    } else{
        $("#list").css({"text-decoration":  "none"});
    }
}); 
}};

EDIT:

I forgot to mention that your code is not working because you are adding your class to the input which is just affecting the checkbox style not the text following it.

For my code to work you just need to modify this line, adding a span to wrap your task. You do not need the change function anymore.

var newObj = $("#list").append("<input id="+itemName+" type=checkbox class="+itemName+"><span>"+task+"</span><br></br>");// makes a new <p> element

SOLUTION:

You can achieve this with plain CSS using :checked pseudo-class and using a span or any other tag that can be used as a selector directly following your input:


JSFiddle


CODE SNIPPET:

 .example:checked + span { text-decoration: line-through; } 
 <input class="example" type="checkbox"><span>Eggs</span> <input class="example" type="checkbox"><span>Milk</span> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM