在jQuery中不能从元素中获取文本

cant get text from an element in jQuery

本文关键字:获取 取文本 元素 不能 jQuery      更新时间:2023-09-26

我有一个HTML设置如下,我试图使用jQuery来访问字体字段的文本。该表有多行,因此是jQuery中的第一行,由于某种原因,我得到了title变量返回的空字符串。谢谢你的帮助!

HTML

<table class="table">
    <tbody>
        <tr>
            <td class="head">
                <a href="link" target="_self">
                    <p>
                        <font>SomeText</font>
                    </p>
                </a>
            </td>
        </tr>
    </tbody>
</table>
jQuery

$('.table').each(function(){
    $(this).filter(function(){
        var data   = $(this);
        title = data.children(".head").text();
        json.array.push({
            "title" : title
            });
    })
})

.head不是.table的子节点。所以.children(".head")不会返回任何元素。你应该用.find代替。

同样,.filter似乎没有必要:

$('.table').each(function(){
    var data = $(this);
    title = data.find(".head").text();
    json.array.push({
        "title" : title
    });
})

带有class head的元素中没有文本,您需要调整选择器以获得实际的字体元素,如下所示:

data.children(".head font").text();