使用 jQuery 从特定 <td> 中提取文本

Using jQuery to pull text from a specific <td>

本文关键字:td 取文本 提取 jQuery 使用      更新时间:2023-09-26

>我正在外部页面上运行 AJAX 查询,并尝试仅从县返回数据。我当前的脚本是从所有表格单元格中提取文本,但我一生都无法让它简单地拉取县名。

当前正在运行的脚本:

$( ".zipCode" ).each(function( intIndex ){
var zipCodeID = $(this).attr('id');
console.log('http://www.uscounties.org/cffiles_web/counties/zip_res.cfm?zip='+zipCodeID);
$.ajax({
    url: 'http://www.uscounties.org/cffiles_web/counties/zip_res.cfm?zip='+zipCodeID,
    type: 'GET',
    success: function(res) {
        var headline = $(res.responseText).find("p").text();
        console.log(headline);
        $('#'+zipCodeID).empty();
        $('#'+zipCodeID).append(headline);
    }
});
});

正在查询的页面的示例:http://www.uscounties.org/cffiles_web/counties/zip_res.cfm?zip=56159

这应该适用于所有输入的 ZIPS。页面布局是一样的,我只是无法获得只返回县的函数。任何帮助或建议都会很棒。谢谢!

由于该页面上完全没有id s 和 class es,您实际上没有太多可继续的。 如果您可以访问该页面的源代码,请在单元格上贴上idclass,让您的生活更加轻松。 如果没有,则必须使用您对页面结构的了解来查找县。 像这样的东西将专门适用于您链接到的那个页面。 如果其他页面有轻微的变化,这将失败:

var headline = $(res.responseText).find("table > tr:eq(2) > td:eq(3)").text();

这假定页面上只有一个表,并且该县始终位于第 2 行的第 3 个单元格中。

你基本上是在屏幕抓取。 我不知何故认为由于跨域和其他事情,您会遇到问题,但这是问题的附属问题。

您需要浏览生成的页面。 假设屏幕上只有一个页面,它看起来像这样:

var retVal = [];
// Basically, for each row in the table...
$('tr').each(function(){
    var pTR = $(this);
    // Skip the header row.
    if (pTR.find('th').length == 0)
    {
        // This is the array of TDs in the given row.
        var pCells = $('td', pTR);
        retVal.push({state:$(pCells[0]).text(), place:$(pCells[1]).text(), county:$(pCells[2]).text()});
    }
});
// retVal now contains an array of objects, including county.
if (retVal.length > 0) 
{
    alert(retVal[0].county);
}
else
{
    alert('Cannot parse output page');
}

解析代码被编写为可扩展的,因此您可以取回所有数据。 有了邮政编码,虽然你可能只会回到一个县,但你肯定会回到更多的地方。 另请注意...由于各种原因,并非每个邮政编码都附加了一个县,但在这种情况下,您应该返回一个空字符串。