如何在不中断任何事件的情况下使用jQuery(或纯JS)替换文本? [英] How to replace text using jQuery (or plain JS) without breaking any events?

查看:79
本文介绍了如何在不中断任何事件的情况下使用jQuery(或纯JS)替换文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在很长一段时间内都在思考以下问题(看起来很简单).我想在双大括号之间更改单词,而不会中断任何事件.

I'm struggling for quite some time with the following question (that looks so simple). I want to change words between double curly brackets without breaking any events.

困难在于我不知道会发生什么事件.所以span上的background-color只是一个例子,但可以是任何东西.

The difficulty lies in the fact that I don't know what events are set. So the background-color on the span is just an example, but could be anything.

这是我的html:

<div class="test">foo <span>bar</span> {{ baz }}</div>

这是我的JS:

$("span").
    css('background-color', 'red').
    click(function(){
       alert('Clicked bar!'); 
    });

$( ".test" ).
    contents().
    each(function(){
       if( $(this).text().indexOf('{{') !== -1 )
       {
           $(this).
               text().
               replace(/{{\s?([^}]*)\s?}}/, "HOW DO I CHANGE {{ baz }} FOR SOMETHING ELSE WITHOUT BREAKING THE EVENT? THIS DOESN'T WORK");
       }
    });

执行以下示例中的操作无效,因为它破坏了span上的操作.

Doing something like the example below wouldn't work because it breaks the action on the span.

$('.test').
    html( 
        $('.test').
            html().
            replace(/{{\s?([^}]*)\s?}}/, 'baq')
    );

推荐答案

要保留元素,您只想替换元素内的文本.您可以创建一个函数,该函数循环遍历元素中的节点并替换文本节点中的文本,并使用任何元素调用自身.这样,您可以替换要保留的元素周围的文本,甚至替换那些元素内的文本:

To preserve the elements you would want to replace only text inside the elements. You can make a function that loops through the nodes in the element and replaces text in the text nodes, and calls itself with any elements. That way you can replace the text around elements that you want to preserve, and even text inside those elements:

$("span").
    css('background-color', 'red').
    click(function(){
       alert('Clicked bar!'); 
    });

function replace(el) {
  var c = el.childNodes;
  for (var i = 0; i < c.length; i++) {
    if (c[i].nodeType == 3) {
      c[i].textContent = c[i].textContent.replace(/{{\s?([^}]*)\s?}}/, "Something else");
    } else {
      replace(c[i]);
    }
  }
}

replace($('.test')[0]);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="test">foo {{ baz }} bar <span>bar {{ baz }} foo</span> foo {{ baz }} foo</div>

这篇关于如何在不中断任何事件的情况下使用jQuery(或纯JS)替换文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆