简体   繁体   English

如何使用jQuery遍历此DOM并检索所需的文本?

[英]How do I traverse this DOM with jQuery and retrieve the required text?

I have one form on a page which has a bunch of sibling h5 tags. 我在页面上有一个表单,其中包含一堆兄弟h5标签。 I'd like to retrieve the text between each h5 tag using jQuery. 我想使用jQuery检索每个h5标签之间的文本。 I'd preferably like to have a callback or be able to do this in a simple looping construct where I can grab the text and make meaningful HTML of it, then insert the final string somewhere else. 我最好喜欢回调或能够在一个简单的循环结构中执行此操作,我可以抓取文本并制作有意义的HTML,然后在其他地方插入最终字符串。

How does one do this with jQuery? 如何用jQuery做到这一点?

This will grab all h5 under the form and alert their text. 这将获取表单下的所有h5并提醒他们的文本。 You can do whatever from there. 你可以从那里做任何事情。

$('#myform h5').each(function() {
    alert($(this).text());
});

By sibling tags you mean they are at the same level than the form, like this?: 通过兄弟标签你的意思是他们与表格处于同一水平,像这样?:

<form id="the-form">
  ...
</form>
<h5>Title 1</h5>
<h5>Title 2</h5>
<h5>Title 3</h5>

If that's correct, you can do something like: 如果这是正确的,你可以这样做:

$("#the-form ~ h5").each(function (){
  // do something with $(this).text()
});

Note the ~, which selects siblings. 注意〜,它选择兄弟姐妹。

Or, if you prefer to send the text to a callback: 或者,如果您希望将文本发送到回调:

function callback( textFound ){
  // do something with textFound
}

$("#the-form ~ h5").each(function (){
  callback( $(this).text() );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM