gpt4 book ai didi

jquery - 使用 jQuery 从元素中获取特定文本内容

转载 作者:行者123 更新时间:2023-12-01 01:03:16 24 4
gpt4 key购买 nike

我需要使用 jQuery 从页面上的元素中提取一些文本,但我不知道如何获取我需要的部分。

这是我的 HTML:

<a href="#" class="song">    Soulstar    <div>by <span class="artist">Musiq Soulchild</span></div></a>

我想提取 .artist 的内容(在本例中为 Musiq Soulchild )。首先,我尝试了这个:

var this_artist = $(this).children().text();alert(this_artist);

这给了我 by Musiq Soulchild (因为 this<a> 元素)。所以我假设我所要做的就是在 .children() 中指定一个选择器方法将范围缩小到 .artist类,像这样:

var this_artist = $(this).children(".artist").text();alert(this_artist);

但这给了我...什么也没有。我也尝试过$(this).children("span").text();同样,也一无所获。

我做错了什么?

最佳答案

.children() 仅遍历直接子级 - 鉴于您的标记 .artist 不是直接子级。使用find()相反:

var this_artist = $(this).find('.artist').text();

关于jquery - 使用 jQuery 从元素中获取特定文本内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9268164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com