jQuery:我将如何替换第n个Child [英] Jquery: How would I replace n-th Child

查看:91
本文介绍了jQuery:我将如何替换第n个Child的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML:

<div id="content">
  <span>SomeContent-->1</span>
  <span>SomeContent-->2</span>
  <span>SomeContent-->3</span>
  <span>SomeContent-->4</span>
  <span>SomeContent-->5</span>
</div>

执行jQuery后的最终结果:

Final result after execution of jQuery:

<div id="content">
  <span>OtherContent-->0</span>
  <span>OtherContent-->9</span>
  <span>OtherContent-->8</span>
  <span>OtherContent-->7</span>
  <span>OtherContent-->6</span>
</div>

我已将content元素存储为var elem = document.getElementById('content') 现在,我想通过选择一对一来替换elem的子级.我尝试使用功能.replaceWith(),但对我不起作用还有其他方法吗?

I have stored the content element as var elem = document.getElementById('content') Now, I want to replace the children of elem by selecting them One by One. I tried to use the function .replaceWith() but didn't work for me Is there any other way?

推荐答案

您只需要使用.html()或.text()

You just need to use .html() or .text()

 $('span', elem).text(function(index, currentValue){ // or use .html for html content
      return "new value";
  });

  $('span', elem).each(function(){
        this.innerHTML = "newContent"; // or $(this).text('newContent') / $(this).html(newContent)
  });

  • .html()
  • .text()
  • .eq(n)
    • .html()
    • .text()
    • .eq(n)
    • 要替换第n个元素的内容,请使用:

      For replacing nth element's content use:

      $('span', elem).eq(n).html(newCOntent); // or .text() where n is 0 indexed.
      

      这篇关于jQuery:我将如何替换第n个Child的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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