将(this)与动态内容jQuery一起使用

using (this) with dynamic content jQuery

本文关键字:jQuery 一起 动态 this      更新时间:2023-09-26

我很难理解使用jQuery添加动态内容。我的代码会将项目添加到列表中,当您单击该列表中的某个项目时,该项目的内容应该是可见的。现在,当我点击一个项目时,所有项目的内容都会显示出来。我试着加(这个),但没用。

$(document).ready(function() {
var hidden = true;
$("#add").click(function() {
    var item = $("#name").val();
    var date = $("#date").val();
    if(item == "") {
        return false;
    }
    var prependItem =
    "<li class='new'>"+
        "<button class='btn btn-default' id='check'></button>"+
        "<span class='item'>&nbsp;"+item+"</span>"+
        "<ul class='sub'>"+
            "<li>"+
                "Due date: 5/3/2015"+
            "</li>"+
        "</ul>"+
    "</li>";
    $(".todo").prepend(prependItem);
    $(".sub").hide();
    $(".form")[0].reset();
    return false;
});
// show sub content
$(".todo").on("click", ".item", function() {
    if(hidden == true) {
        $(".sub").show();
        hidden = false;
    }
    else {
        $(".sub").hide();
        hidden = true;
    }
});
$(".todo").on("click", "#check", function() {
    // line through
})                                      
});

.sub元素是.item的兄弟元素,因此除了使用this获取对引发事件的元素的引用外,还需要使用siblings('.sub')。您也可以使用toggle()来简化代码。试试这个:

$(".todo").on("click", ".item", function() {
    $(this).siblings(".sub").toggle();
});

sub是单击的item的下一个同级,因此您可以像一样使用this和.next()

// show sub content
$(".todo").on("click", ".item", function() {
    $(this).next().toggle();
});

另外,不使用变量来存储隐藏状态,而是使用.thoggle()

使用此

$(".todo").on("click", ".item", function() {
    $(this).children(".sub").toggle();
});