简体   繁体   English

将Jquery附加到div后,如何使用Jquery修改css元素?

[英]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. 我在修改css时遇到麻烦,因此在检查时文本显示通过它的一行。 The check function works and it runs but I am unable to put a line through the specific html element. 检查功能可以正常运行,但是我无法通过特定的html元素插入一行。

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: 您可以使用纯CSS使用:checked伪类,并在输入之后直接使用span或任何其他可用作选择器的标签来实现此目的:


JSFiddle 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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