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

3
我需要使用jQuery从页面元素中提取一些文本,但我无法弄清楚如何获取所需的内容。
这是我的HTML: Soulstar
by Musiq Soulchild
我想提取.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();,同样地,我什么也没得到。

我做错了什么?


1
由于您正在使用this,我们需要知道代码执行的上下文。例如,它是否在事件处理程序内部? - Chris Laplante
这是我点击的<a>元素,因为它在附加到特定<div>内所有锚点的函数中:$("#results a").live("click", function(event){...}); - daGUY
$('.song.artist').text(); $('.歌曲.艺术家').text(); - Mark Schultheiss
1
请注意,.live( 已经在 1.7.1 版本中被废弃,建议使用 .on( - Mark Schultheiss
6个回答

2

.children() 方法只会遍历直接子元素,而在你的标记中 .artist 并不是一个直接的子元素。请使用 find() 方法代替:

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

2
您的选择器不正确,因为.artist不是a元素的直接子元素。相反,您需要使用$(this).find():
var this_artist = $(this).find(".artist").text();
alert(this_artist)  

示例代码

该链接是一个示例代码。

1
你应该使用.find而不是.children.children只搜索直接子元素,而.find会搜索所有后代元素。

0
如果这是您链接的对象,则此代码返回 span 文本:
var this_artist = $(this).find('span').text();
alert(this_artist);

0

使用:

$("#results").on("click","a", function(event){
var myartist = $(this).find('.artist').text();
}); 

0

任意一个

$(this).find("span.artist")

或者

$("span.artist", this)

应该这样做... span 是 div 的子元素,而不是 anchor。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接