【问题标题】:Not getting values from jQuery loop没有从 jQuery 循环中获取值
【发布时间】:2019-06-08 16:22:03
【问题描述】:

我正在尝试使用 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 
]

【问题讨论】:

    标签: jquery node.js nightmare


    【解决方案1】:
    $('.link-title').each(() => {
                item = {
                    "title": $(this).text(),
                    "link": $(this).attr("href")
                };
                links.push(item);
            });
    

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

    【讨论】:

    • 所以你应该这样写: $('.link-title').each(function() { item = { "title": $(this).text(), "link ": $(this).attr("href") }; links.push(item); });
    猜你喜欢
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 2013-09-22
    相关资源
    最近更新 更多