简体   繁体   English

如何删除动态添加的元素?

[英]How to remove element dynamically added?

I have this code, which adds dynamic div right below the textbox but I want to remove it after the user deletes the characters: 我有这段代码,它在文本框下方添加了动态div,但是我想在用户删除字符后将其删除:

The code below doesn't work, I don't see what I am doing wrong 下面的代码不起作用,我看不到我在做什么错

Code from Fiddle 小提琴的代码

See code below: 参见下面的代码:

    $(document).ready(function () {

        $("#searchcontent").keypress(function (e) {
            var dvSearch = $('<div />');
            dvSearch.attr('dvSearch', '1');

            if ($("#searchcontent").val().length >= 2) {
                var pos = $(this).position();
                dvSearch.html("<div>ffff:<div><div>eeee:<div><div>ggggg:<div>").css({
                    top: pos.top + $(this).height() + 18,
                    left: pos.left,
                    width: '300px',
                    position: 'absolute',
                    'background-color': 'Yellow'
                }).insertAfter($(this));
            }
            else {
                $("div[dvSearch='1']").remove();
            }
        });

    });

I would suggest simply having a container ready to receive the result content in your HTML. 我建议仅准备一个容器来接收HTML中的结果内容。 Then you can reduce the problem by either adding the results there or emptying that container. 然后,您可以通过在其中添加结果或清空该容器来减少问题。 In your original code, you were continually adding div elements on every keypress event. 在原始代码中,您一直在每个keypress事件上不断添加div元素。

Also, as others have mentioned, you will want to use .keyup() instead of .keypress() to ensure the value of the input is correct when the event triggers. 另外,正如其他人提到的那样,您将要使用.keyup()而不是.keypress()来确保事件触发时输入的值正确。

HTML 的HTML

<input type="text" id="searchcontent" name="searchcontent" class="txtSearch" maxlength="30" />
<div id="searchresult"></div>

JS JS

$(document).ready(function() {
    $("#searchcontent").keyup(function(e) {
        if ($("#searchcontent").val().length >= 2) {
            var pos = $(this).position();
            $("#searchresult").html("<div>ffff:<div><div>eeee:<div><div>ggggg:<div>");
        }
        else {
            $("#searchresult").empty();
        }
    });
});

jsfiddle jsfiddle

The issue is that keypress is run before the actual value is updated. 问题是在实际值更新之前先运行按键。 So, if the textbox says "hi" and you press backspace, the value of the select is still "hi". 因此,如果文本框显示“ hi”,然后按Backspace键,则select的值仍为“ hi”。

Alter 改变

$("#searchcontent").keypress(function(e){

to

$("#searchcontent").keyup(function(e){

and it solves the issue. 它解决了这个问题。

Updated JS Fiddle 更新了JS小提琴

The problem is that .keypress() does not fire when backspace is pressed. 问题在于,按下退格键时不会触发.keypress()。 Use .keyup() instead. 使用.keyup()代替。

It`s not a good way always run selector for html. 始终运行html选择器不是一个好方法。 Especially global. 尤其是全球。 Save the link to node and remove it by it 将链接保存到节点并通过它删除它

$(document).ready(function () {
   $("#searchcontent").keyup(function (e) {
        var el = $(this),
            // getting link
            dvSearch  = el.data("searchBlock"),
            // getting passed state
            dvPassed = el.data("searchPassed"),
            pos;

        // setting if first run
        if (!dvSearch) {
            dvSearch = $("<div/>");
            // for what is it ?
            dvSearch.attr('dvSearch', '1'); 

            el.data("searchBlock", dvSearch);
            el.data("searchPassed", false);
        }




        if (el.val().length >= 2) {
            pos = el.position();

            // Inserting element if need
            if (!dvPassed) {
                dvSearch.insertAfter(el);
                el.data("searchPassed", true);
            }

            // setting html
            dvSearch.html("<div>ffff:<div><div>eeee:<div><div>ggggg:<div>").css({
                top: pos.top + el.height() + 18,
                left: pos.left,
                width: '300px',
                position: 'absolute',
                'background-color': 'Yellow'
            });
        }
        else {
            dvSearch.remove();
            el.data("searchPassed", false);
        }
    });

});

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

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