为什么我只用$(' a')获得一个元素数组而不是全部?

时间:2015-02-12 07:00:17

标签: javascript jquery html

我正在编写一个脚本来抓取不使用jQuery的论坛的每个线程内容。所以我添加了js代码来加载jQuery(最后会显示)。

当我在Chrome控制台中输入$.fn.jquery并返回'1.11.1'时,它确实有效。我可以轻松地使用jQuery吗?

当然不是。我输入$('a')并且它只返回[<a href="index.php?">foo</a>],它在数组中只有 ONE 元素,但此论坛确实有越来越多的超链接。

已更新:如果我输入$('a[href=bar]')(或其他ID),则会返回[<a href="index.php?">bar</a>]

我尝试其他方式,例如$('*').find('a'),它会返回相同的内容。

BTW,论坛中只有一个iframe。

enter image description here

任何人都有想法或遇到同样的问题吗?


下面是加载jQuery的js代码。

  (function () {

    function loadScript(url, callback) {

        var script = document.createElement("script")
        script.type = "text/javascript";

        if (script.readyState) { //IE
            script.onreadystatechange = function () {
                if (script.readyState == "loaded" || script.readyState == "complete") {
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else { //Others
            script.onload = function () {
                callback();
            };
        }

        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    }

    loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js", function () {

         //jQuery loaded
         console.log('jquery loaded');

    });

})();

3 个答案:

答案 0 :(得分:0)

这应该做的工作

var link = $("a").map(function() {
return this.innerHTML;
}).get();

console.log(link.join());

将要从html中检索的内容放入函数中。

答案 1 :(得分:0)

假设您在这里使用谷歌浏览器。这似乎是在谷歌Chrome控制台窗口中输入的内容在父(或根)页面的上下文中执行的问题。

更改背景。

了解如何在jsfiddle中完成。

enter image description here

更改背景:

enter image description here

现在你可以做任何你想做的事了:

enter image description here

答案 2 :(得分:0)

大家:

我发现了论坛的问题。我在jquery.js中调试并在

之后找到
push.apply( results,
    newContext.querySelectorAll( newSelector )

(它位于第864行,https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js

results只需在其中输入一个元素,然后我在论坛中找到另一个名为common.js的js定义function push,如下所示:

Array.prototype.push = function(value) {
    this[this.length] = value;
    return this.length;
}

所以function push做错了。

这个问题可能不是一个好问题,因为这种情况太特殊了。但我学会了如何从js代码调试,不要任意覆盖原生函数。

最后,感谢所有帮助过我的人。