html.replace 导致事件失效?

我本来有个点击复制的事件,用的clipboard.js
现在我加了下面这个html.replace后导致复制失效。
请问如何修改下面的代码,谢谢。

    <div id=content>
<div id=list3 class=copy-btn data-clipboard-target=#list3> 点击自动复制这些内容</div>
</div>


$('.copy-btn').click(function(){
    let id = $(this).attr('id')
    copy('#'+id)
    })
    function copy(id){
    let clipboard = new ClipboardJS(id);}

上面这是点击复制。下面是高亮关键词并自动定位到关键词位置。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jquery页面内容查找</title>
    <style>
        .disshow {
            display: none;
        }
 
        .highlight {
            color: #fb4232;
            background-color: #ff0;
            border: 1px solid transparent;
        }
 
        .highlight.select {
            background-color: #ddd;
            border: 1px solid #999;
        }
 
        .search {
            position: relative;
            margin-bottom: 40px;
        }
 
        .searchTip {
            padding: 5px 10px;
            position: absolute;
            top: 10px;
            left: 0;
            background: #333;
            box-shadow: 4px 5px 7px 1px #999;
            color: #fff;
            opacity: 0.9;
        }
    </style>
</head>
<body>
<div class="search">
    <input id="key-word" class="key-word" value="请输入搜索内容"/>
    <button id="search-button">搜索</button>
    <p class="searchTip disshow"></p>
</div>

<script src="https://cdn.bootcss.com/jquery/2.2.0/jquery.js"></script>
 
<script>
    (function ($) {

        $.fn.fixDiv = function (options) {
            var defaultVal = {
                top: 20
            }
            var obj = $.extend(defaultVal, options)
            $this = this;
            var _top = $this.offset().top;
            var _left = $this.offset().left;
            $(window).scroll(function () {
                var _scrollTop = $(document).scrollTop();
                if (_scrollTop > _top) {
                    $this.offset({
                        top: _scrollTop + obj.top,
                        left: _left
                    });
                } else {
                    $this.offset({
                        top: _top,
                        left: _left
                    });
                }
            });
            return this;
        }
    }(jQuery))
 
    $(function () {
//        调用fixDiv方法
        $('.search').fixDiv({top: 10});
        $('#search-button').click(hightLight);
//        回车进行搜索
        $('.key-word').keydown(function (e) {
            var key = e.which;
            if (key == 13) hightLight();
        })
 
        var index = 0;
        var historyText;
 
        function hightLight() {
            clearSelection();
            var flag = 0;
 
            var inpText = $('#key-word').val();
            var regExp = new RegExp(inpText, 'g');
            var content = $('#content').text();
            if ($.trim(inpText) == '') {
                showTips('请输入查找内容');
                return;
            }
            if (!regExp.test(content)) {
                showTips('未找到匹配项');
                return;
            } else {
                if (historyText != inpText) {
                    index = 0;
                    historyText = inpText;
                }
            }
            $('#content p').each(function () {
                var html = $(this).html();
                var newhtml = html.replace(regExp, '<span class="highlight">' + inpText + '</span>');
                $(this).html(newhtml);
                flag = 1;
            })
            if (flag == 1) {
                var _top = $(".highlight").eq(index).offset().top;
                $(".highlight").eq(index).addClass('select').siblings('.highlight').removeClass('select');
                $("#search-button").html("查找下一个");
                $("html, body").animate({scrollTop: _top-50});
                index++;
                if (index > $(".highlight").size() - 1) {
                    index = 0;
                }
            }
        }
//    清除选择
        function clearSelection() {
            $('#content p').each(function () {
                $(this).find('.highlight').each(function () {
                    $(this).replaceWith($(this).html());
                })
            })
        }
//    显示提示信息
        function showTips(text) {
            $('.search .searchTip').text(text);
            $('.search .searchTip').removeClass('disshow').show();
            setTimeout(function () {
                $('.search .searchTip').fadeOut()
            }, 2000);
        }
    })
</script>
</body>
</html>
阅读 2k
2 个回答

我不知道你的 div#content .copy-btn #list3 的关系,我自己补了一些代码,高亮后的复制依然可用。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>jquery页面内容查找</title>
    <style>
      .disshow {
        display: none;
      }

      .highlight {
        color: #fb4232;
        background-color: #ff0;
        border: 1px solid transparent;
      }

      .highlight.select {
        background-color: #ddd;
        border: 1px solid #999;
      }

      .search {
        position: relative;
        margin-bottom: 40px;
      }

      .searchTip {
        padding: 5px 10px;
        position: absolute;
        top: 10px;
        left: 0;
        background: #333;
        box-shadow: 4px 5px 7px 1px #999;
        color: #fff;
        opacity: 0.9;
      }
    </style>
  </head>
  <body>
    <div class="search">
      <input id="key-word" class="key-word" value="请输入搜索内容" />
      <button id="search-button">搜索</button>
      <p class="searchTip disshow"></p>
      <div id="content">
        <div id="list3" class="copy-btn" data-clipboard-target="#list3">
          <p>是打发斯蒂芬</p>
          <p>打发顺丰未发</p>
          <p>123456</p>
          <p>打发顺丰未发</p>
          <p>是打发斯蒂芬</p>
        </div>
      </div>
    </div>

    <script src="https://cdn.bootcss.com/jquery/2.2.0/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.10/clipboard.min.js"></script>

    <script>
      (function ($) {
        $.fn.fixDiv = function (options) {
          var defaultVal = {
            top: 20,
          };
          var obj = $.extend(defaultVal, options);
          $this = this;
          var _top = $this.offset().top;
          var _left = $this.offset().left;
          $(window).scroll(function () {
            var _scrollTop = $(document).scrollTop();
            if (_scrollTop > _top) {
              $this.offset({
                top: _scrollTop + obj.top,
                left: _left,
              });
            } else {
              $this.offset({
                top: _top,
                left: _left,
              });
            }
          });
          return this;
        };
      })(jQuery);

      $(function () {
        //        调用fixDiv方法
        $(".search").fixDiv({ top: 10 });
        $("#search-button").click(hightLight);
        //        回车进行搜索
        $(".key-word").keydown(function (e) {
          var key = e.which;
          if (key == 13) hightLight();
        });

        var index = 0;
        var historyText;

        function hightLight() {
          clearSelection();
          var flag = 0;

          var inpText = $("#key-word").val();
          var regExp = new RegExp(inpText, "g");
          var content = $("#content").text();
          if ($.trim(inpText) == "") {
            showTips("请输入查找内容");
            return;
          }
          if (!regExp.test(content)) {
            showTips("未找到匹配项");
            return;
          } else {
            if (historyText != inpText) {
              index = 0;
              historyText = inpText;
            }
          }
          $("#content p").each(function () {
            var html = $(this).html();
            console.log("html", html);
            var newhtml = html.replace(
              regExp,
              '<span class="highlight">' + inpText + "</span>"
            );
            $(this).html(newhtml);
            flag = 1;
          });
          if (flag == 1) {
            var _top = $(".highlight").eq(index).offset().top;
            $(".highlight")
              .eq(index)
              .addClass("select")
              .siblings(".highlight")
              .removeClass("select");
            $("#search-button").html("查找下一个");
            $("html, body").animate({ scrollTop: _top - 50 });
            index++;
            if (index > $(".highlight").size() - 1) {
              index = 0;
            }
          }
        }
        //    清除选择
        function clearSelection() {
          $("#content p").each(function () {
            $(this)
              .find(".highlight")
              .each(function () {
                $(this).replaceWith($(this).html());
              });
          });
        }
        //    显示提示信息
        function showTips(text) {
          $(".search .searchTip").text(text);
          $(".search .searchTip").removeClass("disshow").show();
          setTimeout(function () {
            $(".search .searchTip").fadeOut();
          }, 2000);
        }
      });

      (function () {
        $(".copy-btn").click(function () {
          let id = $(this).attr("id");
          copy("#" + id);
        });
        function copy(id) {
          let clipboard = new ClipboardJS(id);
          console.log("复制成功");
        }
      })();
    </script>
  </body>
</html>

这样做相当于替换成新的节点,新节点上没有绑事件,所以当然会失效。

解决方案有三个:

  1. 只替换文字
  2. 替换节点之后重新绑事件
  3. 把事件绑在上层节点,利用冒泡机制解决
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题