Typescript 在子元素上应用选择器
我没有找到在元素上应用选择器的方法(版本1.0.0-rc.3)。使用会引发错误Typescript 在子元素上应用选择器,typescript,cheerio,Typescript,Cheerio,我没有找到在元素上应用选择器的方法(版本1.0.0-rc.3)。使用会引发错误 const xmlText = ` <table> <tr><td>Foo</td><td/></tr> <tr><td>1,2,3</td><td>number</td></tr> <tr><td>A,B</td><td
const xmlText = `
<table>
<tr><td>Foo</td><td/></tr>
<tr><td>1,2,3</td><td>number</td></tr>
<tr><td>A,B</td><td>char</td></tr>
<!-- more rows -->
</table>
<table>
<tr><td>Bar</td><td/></tr>
<!-- more rows -->
</table>
`
const $ = cheerio.load(xmlText)
$('table').each((i, table) => {
// TODO if first row contains Foo then map the following rows
if (table.find("td:contains('Foo')").length > 0) {
// ...
}
})
从零开始编写,我相信有更好的方法:
$('table').each((i, table) => { if ($(table).find("td:contains('Foo')").length > 0) {$('tr', table).each((i, tr)=>{console.log($(tr).text())})} })
我在方法的文档中找到了答案。您必须将给定的
元素
像$(元素)
一样包装起来
最后我解决了这个问题
const $ = cheerio.load(xmlText)
const isFooTable = (i: number, e: CheerioElement) =>
$('td', e).first().text() === 'Foo'
const result: { value: string; type: string }[] = []
$('table')
.filter(isFooTable)
.find('tr')
.slice(1)
.each((_, tr) => {
const tds = $(tr).find('td')
result.push({
value: tds.first().text(),
type: tds.last().text(),
})
})
if ($(table).find("td:contains('Foo')").length > 0) {
const $ = cheerio.load(xmlText)
const isFooTable = (i: number, e: CheerioElement) =>
$('td', e).first().text() === 'Foo'
const result: { value: string; type: string }[] = []
$('table')
.filter(isFooTable)
.find('tr')
.slice(1)
.each((_, tr) => {
const tds = $(tr).find('td')
result.push({
value: tds.first().text(),
type: tds.last().text(),
})
})