Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery-使动态创建的DIV在单击时删除自身_Javascript_Jquery_Html_Css - Fatal编程技术网

Javascript jQuery-使动态创建的DIV在单击时删除自身

Javascript jQuery-使动态创建的DIV在单击时删除自身,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我已经为此挣扎了一段时间了。真希望有人能帮我 我试图使div是可移动的,当你点击他们。 他们有一个css类“tag show”,可以添加和删除(这很有效),所以我想选择器似乎很好 为什么$(this).remove()不起作用 $(document).ready(function() { // selectors var module = $(".divCreate"); var list = module.find(".listTag"); var button = module.find("

我已经为此挣扎了一段时间了。真希望有人能帮我

我试图使div是可移动的,当你点击他们。 他们有一个css类“tag show”,可以添加和删除(这很有效),所以我想选择器似乎很好

为什么$(this).remove()不起作用

$(document).ready(function() {
// selectors
var module = $(".divCreate");
var list = module.find(".listTag");
var button = module.find(".divButton");

// the actual issue
button.click(function() {
        list.append("<div class='tag'>Tag</div>");
        setTimeout(function() {
            list.find(".tag").last().addClass("tag-show").on("click", function() {
                $(this).removeClass("tag-show");
                setTimeout(function() {
                    $(this).remove();
                },190);
            });
        },40);

})
$(文档).ready(函数(){
//选择器
变量模块=$(“.divCreate”);
var list=module.find(“.listTag”);
var button=module.find(“.divButton”);
//实际问题
按钮。单击(函数(){
列表。附加(“标签”);
setTimeout(函数(){
list.find(“.tag”).last().addClass(“tag show”).on(“click”,function()){
$(this.removeClass(“标记显示”);
setTimeout(函数(){
$(this.remove();
},190);
});
},40);
})

}))

setTimeout
回调中不再引用
div
。您可以将回调绑定到
div
或执行以下操作:

var $this = $(this);
setTimeout(function() {
    $this.remove();
},190);
“this”在setTimeout中丢失其上下文。 添加一个包含该变量的变量,并改用该变量。 像这样


我认为这会解决问题。

您应该使用jQuery
.on()
函数,而不是
。单击()
,因为它适用于动态创建的元素。然后,您也不必在每次动态添加元素时将其应用于元素

$(document).ready(function(){})中的代码的其他地方添加此事件处理程序:

$('.listTag').on('click', 'div.tag', function() {
    $(this).remove();
});

它应该适用于与
div.tag
选择器匹配的任何元素。

不确定您要完成什么,但这可能是完成相同任务的更好方法

// selectors
var module = $(".divCreate");
var list = module.find(".listTag");
var button = module.find(".divButton");

// the actual issue
button.click(function() {
    list.append("<div class='tag'>Tag</div>");
})

$(document).on('click','.tag', function(){
    $(this).remove();
});
//选择器
变量模块=$(“.divCreate”);
var list=module.find(“.listTag”);
var button=module.find(“.divButton”);
//实际问题
按钮。单击(函数(){
列表。附加(“标签”);
})
$(文档).on('单击','.tag',函数(){
$(this.remove();
});

我对您的代码做了一些改进,在需要的地方添加了注释。只需检查下面的代码及其注释

remove的问题是,您的案例中的
this
正在“触发”最近的父元素,即
setTimeout
,而不是clicked元素

为了更好地理解,请尝试调用
console.log(this)内部超时函数并单击函数,您将看到差异

我做了一个可以帮助您更好地理解的示例(打开开发人员工具以查看控制台结果)

$(文档).ready(函数(){
//当您将DOM元素保留在变量中时,最好将$放在开头
变量$module=$(“.divCreate”);
//比.find()快
var$list=$(“.listTag”,$module);
//无法使用变量调用“on”
//变量$button=$(“.divButton”,$module);
//通过文档调用,因为我们需要处理动态添加的元素-检查事件委派
$(文档)。在(“单击”、“.divButton”上,函数(){
$list.append(“标签”);
setTimeout(函数(){
//一些改进
$(“.tag”,$list.last().addClass(“标记显示”);
}, 40);
//如果您将divButton附加到锚元素,请保留此选项
//用于防止默认错误-在本例中,将“#”添加到url
返回false;
});
//不需要在该事件内创建事件
$(文档)。在(“单击“,”.tag show“,函数()上){
//因为我们多次使用一个元素,所以最好
//将它添加到变量中以避免性能问题-js缓存它并调用该变量
var$el=$(this);//我们需要的“this”
$el.removeClass(“标签展示”);
setTimeout(函数(){
//这里的'this'返回窗口的一些属性(setTimeout所属的位置),我们需要调用上面缓存的元素
//(上面的“this”包含我们需要的内容)
$el.remove();
}, 190);
}); 
});

注意:仍然不理解为什么需要这些超时,但这取决于您,可能您需要更大的间隔:D

因此,首先单击“.divButton”,它会添加类,然后单击“.tag”它会删除它?不需要$(self)因为self已经是一个jQuery对象了。标记jQuery变量
$self
也很有用——这样你就可以一目了然地知道哪些内容对新创建的
div.tag
元素不起作用。这应该是:
$('.listTag')。在('click','div.tag')…
Ahh,是的,我将对on代码进行更改,但您不同意使用.on()函数是比DRGA的答案更好的实践吗?我完全同意。我们不能期望每个人都已经知道这个概念。这就是为什么我宁愿遵循作者的观点。这是一个糟糕的实践吗?
$
前缀意味着它是
this
的jQuery对象(
div.tag
元素)是的,我知道-使用$引用jquery对象是一种很好的做法-但是不知道这一点的人最终会认为这是错误的:D-只是一些想法OK:D也许我应该建议
绑定
/
调用
/
应用
你在开玩笑吗?这比阅读容易数万亿倍,并且设置了点击events全局,而不是在另一次单击事件之后和设置超时延迟之后,这比原始代码要好。唯一的问题是范围没有那么受限(我们不知道是否有其他
。标记
元素在
列表之外).但我相信这不值得投反对票@Toni@Orland解释为什么要比说你是对的更好。我认为这更好,因为你只需要绑定到一个元素(祖先),而不是绑定到每个实例
// selectors
var module = $(".divCreate");
var list = module.find(".listTag");
var button = module.find(".divButton");

// the actual issue
button.click(function() {
    list.append("<div class='tag'>Tag</div>");
})

$(document).on('click','.tag', function(){
    $(this).remove();
});
$(document).ready(function() { 
    // when you keep DOM elements in variables is better to put $ in the beginning
    var $module = $(".divCreate");

    // faster than .find()
    var $list = $(".listTag", $module);

    // can not call 'on' with variable
    //var $button = $(".divButton", $module);

    // called through document since we need to handle dynamic added elements - check event delegation
    $(document).on("click", ".divButton", function() {
            $list.append("<div class='tag'>Tag</div>");

            setTimeout(function() {
                // some improvments
                $(".tag", $list).last().addClass("tag-show");
            }, 40);

            // Just keep this if you have divButton attached to an anchor element
            // Useful for preventing default behvaiour - in this case adding "#" to url
            return false;
    });

    // Do not need to create the event inside that event
    $(document).on("click", ".tag-show", function() {
        // Since we use an element more than once is better to
        // add it into a variable to avoid performance issues - js caches it and call the variable
        var $el = $(this); // our needed 'this'
        $el.removeClass("tag-show");

        setTimeout(function() {
            // 'this' here returns some properties of window (where setTimeout belongs), we need to call element cached above 
            //(the 'this' above contains what we need) 
            $el.remove();
        }, 190);
    }); 
});