简体   繁体   English

删除附加的文本,点击它

[英]Remove appended text clicking on it Jquery

I'm trying to find easiest and cleaner way to append and remove on appended span, div or text. 我试图找到最简单,最干净的方法来在附加的跨度,div或文本上附加和删除。 Here is the code. 这是代码。 What could be wrong? 有什么事吗

/* HTML CODE */
<div id="appendHere" style="padding:10px;border:solid 1px red"></div>

/* Jquery CODE */
$('#appendHere').live('click' , function() {
    $('#appendHere').append('<span style="padding:10px;border:solid 1px green;">Simple text</span>');
});

$('#appendHere span').live('click' , function() {
    $(this).remove();
});

DEMO 演示

you can try to use .toggle() 您可以尝试使用.toggle()

Example : 范例:

$('#appendHere').on('click' , function(e) {
 $('#appendHere span').toggle();
});

depending on which jQuery version you are using. 取决于您使用的jQuery版本。 Your use of .live() might be your first issue. 您对.live()可能是您的第一个问题。 try instead .on() example: 尝试改用.on()示例:

$(document).on('click', '#appendHere span', function(){$(this).remove();});

You could also just try something like 您也可以尝试类似

<style>
#addHere{padding:10px;border:solid 1px red;}
#addHere span{padding:10px;border:solid 1px green;}
</style>

<div id="appendHere" data-has_span="false"></div>
$(document).on('click', '#appendHere', function()
{
    $elem = $(this);
    if($elem.data('has_span') == "false")
    {
        $elem.prop('data-has_span', 'true').append('<span>Text here</span>');
    }
    else
    {
        $elem.prop('data-has_span', 'false').find('span').remove();
    }
});

You'd better not use live , try instead .bind() or .on() 您最好不要使用live ,而是尝试.bind().on()

The question is when you click span , div is clicked and time 问题是当您单击spandivtime

so you can try to do it like this: 因此您可以尝试这样做:

$("appendHere").on("click", function(e) {
    if(!$(this).is($(e.target))) {
        return false;
    }
    $("<span>Text here</span>").appendTo($(this)).on("click", function() {
         $(this).remove();
    });
});

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

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