如何从第一个<a> tag from each element</a>中选择文字

时间:2013-08-28 14:39:03

标签: jquery jquery-selectors

我有一个事件表,我需要从每个事件中获取事件名称。

var event_names = new Array();  // Initialise to avoid errors
$('td.event_name a', '#the-list').each(function(){
    console.log($(this).text());
    event_names.push($(this).text());
});

但是,这会失败,因为<a>中有多个td.event_name标记,我只需要第一个。

我也试过这个,但我收到错误$(this).$... is not a function

var event_names = new Array();  // Initialise to avoid errors
$('td.event_name', '#the-list').each(function(){
    console.log($(this).$('a:first').text());
    event_names.push($(this).$('a:first').text());
});

有人知道如何绕过这个吗?

这是一些来源,仅适用于<td>个元素之一。我在这段代码中看不到任何obvioius选择器(我无法改变它)。

<td class="event_name column-event_name">
    <label><strong><a title="Edit this event" href="admin.php?page=dd-options-edit-event&amp;event=126" class="edit">
        Test Event
    </a></strong></label>
    <img style="display: none; margin-left: 10px;" src="http://test.dynedrewett.com/wp-admin/images/wpspin_light.gif" alt="" class="waiting">
    <div class="row-actions">
        <span class="edit"><a title="Edit this event" href="admin.php?page=dd-options-edit-event&amp;event=126" class="edit">Edit</a> | </span>
        <span class="inline hide-if-no-js"><a title="Quick edit this event" href="#" class="editinline">Quick Edit</a> | </span>
        <span class="copy"><a title="Copy this event" href="#" class="single-copy">Copy</a> | </span>
        <span class="delete"><a title="Delete this event" href="#" class="single-delete">Delete</a> | </span>
        <span class="open"><a target="_blank" title="Close this event" href="#" class="single-switch-state">Close</a> | </span>
        <span class="view"><a target="_blank" title="View this event" href="http://test.dynedrewett.com/events/?e=126" class="single-view">View</a> | </span>
        <span class="invitations"><a title="Manage invitations to this event" href="http://test.dynedrewett.com/wp-admin/admin.php?page=dd-options-event-invitations&amp;event=126" class="single-view">Invitations</a></span>
    </div>
</td>

4 个答案:

答案 0 :(得分:1)

使用:first选择器,如下所示:

$('td.event_name a:first', '#the-list').each(function(){
    console.log($(this).text());
    event_names.push($(this).text());
});

作为参考,由于语法错误,您的第二次尝试获得$(this).$ is not a function,它应该看起来像以下任何一种:

console.log($('a:first', this).text());
console.log($(this).find('a:first').text());

答案 1 :(得分:1)

$('td.event_name a:first'); 

$('td.event_name', '#the-list').each(function(){
    console.log( $(this).find('a:first') );
});

$('td.event_name', '#the-list').each(function(){
    console.log( $(this).children('a:first') );
});

答案 2 :(得分:1)

这对我有用:

$('td.event_name').each(function(i, td) {
     console.log($(td).find('a:first').text());
});

here

答案 3 :(得分:1)

怎么样:

var event_names = new Array();  // Initialise to avoid errors
$('td.event_name').each(function(){
  console.log($(this).find('a').first().text());
  event_names.push($(this).find('a').first().text());
});