简体   繁体   English

通过索引从 Jquery 选择器中获取元素

[英]Get elements from a Jquery selector via index

I need to iterate the elements of a jQuery selector and obtain certain data from each element.我需要迭代 jQuery 选择器的元素并从每个元素获取某些数据。 More specifically, I need to obtain the <p> tags from them.更具体地说,我需要从他们那里获取<p>标签。
The function .get(index) works well, and it gets the correct element, but then I can't obtain the <p> elements.函数.get(index)运行良好,它获取了正确的元素,但是我无法获取<p>元素。

var n_rows = $('#r_data_5').text();
var data = $('#datos_ocultos > ul > li');
var index = 0;
for (let i = 0; i< parseInt(n_rows); i++){
 for(let j=index; j<4;j++){
  var a = data.get(index).find('#r_data_0').text(); //this is getting an error
 }
}
<div id="datos_ocultos" style="display: none;">
 <p class="report_data" id="r_data_5">
  <t t-esc="number_rows" />
  </p>
  <ul>
   <t t-foreach="report_ids" t-as="report">
    <t t-if="report.teacher_id and report.subject_id">
     <li>
      <p class="report_data" id="r_data_0">
       <t t-esc="report.teacher_id.name " />
      </p>
      <p class="report_data" id="r_data_1">
       <t t-esc="report.subject_id.display_name " />
      </p>
      <p class="report_data" id="r_data_2">
       <t t-esc="report.course_id.display_name " />
      </p>
      <p class="report_data" id="r_data_3">
       <t t-esc="report.teacher_id.work_email " />
      </p>
//more code

Error: Uncaught TypeError: data.get(...).find is not a function错误:未捕获的类型错误:data.get(...).find 不是函数

在此处输入图片说明

.get(ix) yields the DOMNode at that index. .get(ix)在该索引处生成DOMNode You want to use .eq(ix) to get the jQuery object, in order to be able to run .find operations etc.您想使用.eq(ix)来获取 jQuery 对象,以便能够运行.find操作等。

You could also use the DOM node as context for the selector:您还可以使用 DOM 节点作为选择器的上下文:

var a = $('.r_data_0', data.get(index)).text();

Note also that I've updated the selector to search by class rather than id.另请注意,我已将选择器更新为按类而不是 id 进行搜索。 This of course wont work without a corresponding change in markup.如果标记没有相应的变化,这当然不会起作用。

You need to make that change, as ID's are supposed to be unique within the document, and selectors are working based on that assumption.您需要进行更改,因为 ID 在文档中应该是唯一的,并且选择器基于该假设工作。

Why not to use simple each iterator?为什么不使用简单的each迭代器?

$('#datos_ocultos ul li').each(function(){
    var a = $(this).find('#r_data_0').text();
});

You can obtain the p tags from html like this:您可以像这样从 html 获取 p 标签:

$('ul li').each(function()
{
  console.log( this.innerHTML); // This is your p tags
});

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

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