jquery - 没有从 jQuery 循环获取值

标签 jquery node.js nightmare

我正在尝试使用 Nightmare.js 和 jquery 获取网站上元素的文本和链接。

我循环遍历具有相同类的每个元素,没有收到错误,但文本和链接为空。

这是我尝试过的:

nightmare
        .goto("https://myanimelist.net/anime/season")
        .wait(2000)
        .evaluate(() => {
            let links = [];

            $('.link-title').each(() => {
                item = {
                    "title": $(this).text(),
                    "link": $(this).attr("href")
                };
                links.push(item);
            });

            return links;   
        })
        .end()
        .then(result => {
            console.log(result);
        })
        .catch(function (error) {
            console.error('Failed', error);
        });

控制台中的输出如下所示:

[ { title: '' }, 
  { title: '' },
  { title: '' },
  ... 99 more items 
]

最佳答案

$('.link-title').each(() => {
            item = {
                "title": $(this).text(),
                "link": $(this).attr("href")
            };
            links.push(item);
        });

在each()方法中,使用普通函数代替。箭头函数使 this 无法按您的预期工作

关于jquery - 没有从 jQuery 循环获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56508128/

相关文章:

javascript - CDATA 真的有必要吗?

javascript - 如何压缩内容使它们适合DIV

javascript - jQuery 函数返回谷歌地图缩放级别

javascript - Webpack 缩小 -p 错误

javascript - 对回调中可访问的相同数据进行多个单元测试

javascript - 为什么警报会重定向我的页面?

mysql - 解码旧mysql UTF8存储...怎么办?

node.js - 尝试将Nightmare .type()与只能通过名称获得的元素一起使用

javascript - 将类作为参数传递给 Nightmare 评估

javascript - 使用 webpack 时加载 Nightmare 时出错