jquery选中一个相同的多个标签

2025-11-15 23:28:49

1、首先我们来定义一个html的网页模版,如下我们在body中定义多个a标签,把他们的class都写成相同的,如下所示

<body><div style="width: 100%;background: aliceblue;height: 100px"><a class="aclass">百度知道</a><a class="aclass">python</a><a class="aclass">jquery</a><a class="aclass">JavaScript</a> </div></body>

jquery选中一个相同的多个标签

2、下面我们开始写js来把a标签中的内容全部取出来,保存到一个字符串中输出,如下我们定义一个atext变量来存储,a标签的文本内容,然后输出,具体如下图所示:

<script>var atext='';$('.aclass').each(function (index,e) {    atext+=$(e).text()})console.log(atext)</script>

jquery选中一个相同的多个标签

jquery选中一个相同的多个标签

3、如果我们不通过class来选取,直接选择a标签也是可以的,前提是该文档中没有其它你不想选取的a标签了,如下图所示,我们可以看出输出结果也是一样的:

js代码修改为如下:

<script>

var atext='';

$('a').each(function (index,e) {

    atext+=$(e).text()

})

console.log(atext)

</script>

jquery选中一个相同的多个标签

4、你可能想,如果 a标签有id,也可以通过id来选取,进行输出,如下所示我们添加a标签的id='aid',然后在修改js,如下所示:

我们发现并不是预期效果,当使用id时候,如果id都相同只会输出第一个

<div style="width: 100%;background: aliceblue;height: 100px"><a class="aclass" id="a_id">百度知道</a><a class="aclass" id="a_id">python</a><a class="aclass" id="a_id">jquery</a><a class="aclass" id="a_id">JavaScript</a></div></body>

js部分:<script>var atext='';$('#a_id').each(function (index,e) {    atext+=$(e).text()})console.log(atext)</script>

如果用开发工具我们发现会报错

jquery选中一个相同的多个标签

jquery选中一个相同的多个标签

5、现实开发中我们或许是直接通过某个div的class或者id来选取a标签的,如下a标签没class,我们通过divclass来获取

<div class="firstdiv" style="width: 100%;background: aliceblue;height: 100px"><a  id="a_id">百度知道</a><a id="a_id">python</a><a  id="a_id">jquery</a><a  id="a_id">JavaScript</a></div></body>

js部分代码:<script>var atext='';$('.firstdiv a').each(function (index,e) {    atext+=$(e).text()})console.log(atext)</script>

jquery选中一个相同的多个标签

jquery选中一个相同的多个标签

6、为什么通过div的class来取比较合适,因为可能多个div下都有a标签,如下,我们写两个div都有a标签,但是我们只需要第二个div中的a标签文本内容:

<div class="firstdiv" style="width: 100%;background: aliceblue;height: 100px"><a >百度知道</a><a >python</a><a >jquery</a><a >JavaScript</a></div><div class="seconddiv" style="width: 100%;background: aliceblue;height: 100px">    <a  >百度知道1112321312312</a>    <a >ertreterteryh</a></div></body>

js代码部分:<script>var atext='';$('.seconddiv a').each(function (index,e) {    atext+=$(e).text()})console.log(atext)</script>

jquery选中一个相同的多个标签

jquery选中一个相同的多个标签

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢