Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery如何替换元素子元素的文本节点_Javascript_Jquery - Fatal编程技术网

Javascript jQuery如何替换元素子元素的文本节点

Javascript jQuery如何替换元素子元素的文本节点,javascript,jquery,Javascript,Jquery,我想替换元素子元素的所有文本 这样,我替换了II的所有文本子项。可能还有其他标记。 不仅是和 我 二, A B 一, 二, 三, C 三, 我想要这样: 我 二, 测试:A 测试:B 测试:1 测试:2 测试:3 测试:C 三, 我试着编写代码,但失败了 为什么.find('*')失败? i ii a b 1 2 3 c iii $('ul.level-2')。查找('*')。筛选(函数(){ 返回this.nodeType==3 }).每个(功能){ th

我想替换元素子元素的所有文本

这样,我替换了
II
的所有文本子项。可能还有其他标记。 不仅是
    • 二,
    • A
    • B
      • 一,
      • 二,
      • 三,
    • C
    • 三,
    我想要这样:

    • 二,
    • 测试:A
    • 测试:B
      • 测试:1
      • 测试:2
      • 测试:3
    • 测试:C
    • 三,
    我试着编写代码,但失败了

    为什么
    .find('*')
    失败?
    
    
    • i
    • ii
      • a
      • b
        • 1
        • 2
        • 3
      • c
    • iii
    $('ul.level-2')。查找('*')。筛选(函数(){ 返回this.nodeType==3 }).每个(功能){ this.textContent='test:'+this.textContent; }); //$('ul.level-2').children().filter(函数(){ //返回this.nodeType==3 //})。每个(函数(){ //this.textContent='test:'+this.textContent; // });
    您需要的是递归:

    function recursivelyChangeText($node, transformFunc) {
      var children = $node.children()
      if(children.length > 0) {
        for(var i = 0; i < children.length; i++) { 
          recursivelyChangeText($(children[i]), transformFunc)
        }
      } else {
        $node.text(transformFunc($node.text()))
      }
    }
    
    recursivelyChangeText($('ul.level-2'), function(text) {
      return `test: ${text}`
    })
    
    函数递归更改文本($node,transformFunc){
    var children=$node.children()
    如果(children.length>0){
    对于(var i=0;i
    这是一个密码笔:
    作者:Matt Black()。

    不仅
  • ,可能还有其他标签。所以我尝试使用
    find('*')
    。递归是个好主意!感谢但是,为什么
    .find('*')
    失败了呢?哦!我解决它!文本节点不是
    元素
    ,因此
    查找('*')
    无法捕获它。我发现
    contents()
    可以捕获它
    function recursivelyChangeText($node, transformFunc) {
      var children = $node.children()
      if(children.length > 0) {
        for(var i = 0; i < children.length; i++) { 
          recursivelyChangeText($(children[i]), transformFunc)
        }
      } else {
        $node.text(transformFunc($node.text()))
      }
    }
    
    recursivelyChangeText($('ul.level-2'), function(text) {
      return `test: ${text}`
    })