繁体   English   中英

如何选择所有相同的元素并在jQuery中获取每个ID

[英]How to select all same elements and get each id in jQuery

我不会选择体内的所有section标签并获取每个id属性。 我正在使用以下逻辑:

<body>
  <section id="header"></section>
  <section id="content" ></section>
</body>

我想要实现的理想“幻想”代码:

var select_all_section = $('body * section');
var sec_id = select_all_section.attr('id');

console.log(sec_id);
//OUTPUT: header
//OUTPUT: content

我的实际代码

var select_all_section = $('body > section');
var sec_id = select_all_section.attr('id');

console.log(sec_id);
//OUTPUT: header

您是否尝试过.map

 $(function() { var select_all_section = $('section'); var sec_id = select_all_section.map(function() { return this.id; }); console.log(sec_id) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section id="header"> </section> <section id="content"> </section> 

好的,我不知道为什么需要它,但是这是一种单独输出它们的方法。

 var $ids = $('section'); $ids.each(function(i,e){ console.log($(e).attr('id')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section id="header" > </section> <section id="content" > </section> 

编辑:实际上,我认为http://api.jquery.com/jQuery.map/会比这个答案更好。

$("section")将使您已经拥有所有元素的集合。

所以你可以直接去

$("section").css({color:"red", fontSize:"24px"});

或者如果您真的需要ID来使用它来做更多有趣的事情...

使用.prop()

.prop( propertyName, function )将访问所需的属性

 $("section").prop("id", function(idx, val){ console.log(val); }); 
 <section id="header"></section> <section id="content"></section> <section id="footer"></section> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

使用.map()

 var sectionIDs = $("section").map(function() { return this.id; }).get(); console.log( sectionIDs.join("\\n") ); // Join with newline console.log( sectionIDs ); // Show as array 
 <section id="header"></section> <section id="content"></section> <section id="footer"></section> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

使用.each()

如果你需要做更多的这种方法是有用的this势必每这些元素相关的东西,但好了,这里有一个简单的例子

 $("section").each(function() { console.log( this.id ); // Or using jQuery // console.log( $(this).prop("id") ); }); 
 <section id="header"></section> <section id="content"></section> <section id="footer"></section> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

使用纯JavaScript

 Array.from(document.querySelectorAll("section")).forEach( e => console.log(e.id) ); 
  <section id="header"></section> <section id="content"></section> <section id="footer"></section> 

暂无
暂无

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

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