【问题标题】:Traversing DOM with jquery使用 jquery 遍历 DOM
【发布时间】:2016-03-18 19:32:48
【问题描述】:

如果我有以下 div 标签...

<!doctype html>
<div id="idea">
  <p class="news">hello world!</p>
  <p class="news">hello world!</p>
  <p class="news">hello world!</p>
  <p class="news">hello world!</p>
</div>

在 jquery 中,如果我想使用 div id 更改最后一个 p 标签并使用第二个 p 元素类来更改 Hello world!到别的东西。我的努力(不起作用):

  $(document).ready(function) {
    $('#idea:last').html("something else");
  }
  $(document).ready(function) {
    $('.newsbanner[1]').html("something else");
  }

【问题讨论】:

  • 看看你的格式在这里,你需要将代码缩进4个空格才能正确显示。提交问题时阅读信息。
  • 哦,快,就像它更新了一样。谢谢汤姆。
  • 谢谢。对上述有什么想法吗?
  • 你的 HTML 中的 newsbanner 类在哪里?我只看到“新闻”类的元素

标签: jquery dom traversal


【解决方案1】:

您可以使用 :nth-of-type() 选择器。检查这个document

【讨论】:

    【解决方案2】:
    $('.news:nth-child(2)').html("something else");
    

    将更改第二个“.news”html

    您尝试使用数组的示例不正确。您需要先声明数组。从 css 技巧中阅读 nth-child recepies,它们对于在 JS 中查找元素很有用。

    https://css-tricks.com/useful-nth-child-recipies/

    更新:

    // Selects using CSS selectors the second p element, .text() changed the 
    // html elements content and .addClass() adds the class. 
    $('#idea p:nth-child(2)').text('something else').addClass('someClass');
    // Selects the last element
    $('#idea p:last-of-type').text('something else');
    

    https://jsfiddle.net/516crdLd/

    【讨论】:

    • 感谢您的提示,当我使用代码时,第一个会改变一切:$('#newsblock:last-child').html("something else");。另一个根本不起作用。
    • 好的,根据您的要求:“您想使用父母 ID 更改最后一个 P 标签 html,并为第二个 P 标签添加一个类并更改其文本”更新了我的回答。
    猜你喜欢
    • 2010-09-21
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    相关资源
    最近更新 更多