【问题标题】:How to trigger an event when a particular HTML element is removed automatically?自动删除特定 HTML 元素时如何触发事件?
【发布时间】:2018-02-11 17:58:41
【问题描述】:

代码概述:此代码包含一个可编辑的 div 部分。在 div 下方,有一个按钮,用于创建 span 元素,在 span 元素中插入文本“tag”,最后将 span 元素附加到该可编辑 div 中

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
    <style type="text/css">
        #sample-div
        {
            border-style: solid;
            border-width: 1px;
            border-color: black;
            height:100px;
            overflow: auto;
        }
    </style>
    <script type="text/javascript">
        function addTags()
        {
            var tag = document.createElement("span");
            tag.className = "$(tag)"
            tag.innerHTML = "tag";
            tag.contentEditable = false;
            $('#sample-div').append(tag);
        }

        $(document).ready(function(){
            $('span').keyup(function(){
                if(!this.value)
                {
                    alert('this is empty');
                }
            });
        });
    </script>
</head>
<body>
 <div id="sample-div" contenteditable="true"></div>
 <input type="button" value="date" id="sample-tags" onclick="addTags()">
</body>
</html>

一般观察:当我在 div 中输入内容然后单击按钮时,HTML DOM 将变为:

<div id="sample-div" contenteditable="true">
    this is a <span class="$(tag)" contenteditable="false">tag</span>
</div>

请注意,文本“this is a”是我在 div 元素中键入时提供的。当我点击输入按钮时出现“标签”

期望/尝试实现:当我删除span中的文本时,DOM会变成:

<div id="sample-div" contenteditable="true">
    this is a
</div>  

所以,我的目标是在删除 span 中的文本时获取元素 span 被删除的信息。我试图通过执行以下操作来实现这一点,这是不正确的:

$(document).ready(function(){
    $('span').keyup(function(){
        if(!this.value)
        {
            alert('this is empty');
        }
    });
});

所以,我的问题是如何在 DOM 删除 span 元素时收到“这是空的”消息?

【问题讨论】:

    标签: javascript jquery html dom


    【解决方案1】:

    您可以将变量用作“标记”计数器。
    当 div 中出现的数量标签低于标签计数器时,即被删除。

    var tagCount = 0;
    
    function addTags(){
      var tag = document.createElement("span");
      tag.className = "$(tag)"
      tag.innerHTML = "tag";
      tag.contentEditable = false;
      $('#sample-div').append(tag);
      
      // Increment tagCount
      tagCount++;
    }
    
    
    $(document).ready(function(){
    
      $('#sample-div').keyup(function(){
        if($(this).find("span").length < tagCount){
          alert('One tag was removed');
          
          // Decrement tagCount
          tagCount--;
        }
      });
    
    }); // Ready
    #sample-div{
      border-style: solid;
      border-width: 1px;
      border-color: black;
      height:100px;
      overflow: auto;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="sample-div" contenteditable="true"></div>
     <input type="button" value="date" id="sample-tags" onclick="addTags()">

    【讨论】:

    • tagCount = $(this).find("span").length 可以避免同时删除多个跨度的问题。
    【解决方案2】:

    你可能应该使用MutationObserver

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8" />
        <title></title>
        <style type="text/css">
            #sample-div
            {
                border-style: solid;
                border-width: 1px;
                border-color: black;
                height:100px;
                overflow: auto;
            }
        </style>
    </head>
    <body>
        <div id="sample-div" contenteditable="true"></div>
        <input type="button" value="date" id="sample-tags" onclick="addTags()">
        <script type="text/javascript">
    
            'use strict';
    
            function addTags()
            {
                var tag = document.createElement("span");
                tag.className = "$(tag)"
                tag.innerHTML = "tag";
                tag.contentEditable = false;
                document.getElementById('sample-div').appendChild(tag);
            }
    
            function onTagRemoved(node)
            {
                alert(`node ${node.tagName}.${node.className} removed`);
            }
    
            //
            // https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
            //
    
            // select the target node
            let target = document.querySelector('#sample-div');
    
            // create an observer instance
            let observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
    
                    // console.log(mutation);
    
                    let node = null;
                    for (var i = 0; i < mutation.removedNodes.length; i++) {
                        node = mutation.removedNodes[i];
                        if (/span/i.test(node.tagName)) {
                            onTagRemoved(node);
                        }
                    }
                });
            });
    
            // configuration of the observer:
            let config = { attributes: false, childList: true, characterData: false }
    
            // pass in the target node, as well as the observer options
            observer.observe(target, config);
    
            // later, you can stop obser
            // observer.disconnect();
    
        </script>
    </body>
    </html>
    

    在 Firefox 52 上测试

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 2014-02-28
      • 2012-01-30
      相关资源
      最近更新 更多