我的代码出了什么问题

时间:2010-09-25 15:23:57

标签: javascript jquery append

这是我用javascript写的第一件事,所以我希望它是一个基本的错误

我想在这里实现的目标: 从页面中获取一堆链接,加载内容查询内部链接并将其添加到当前页面上的列表中。

我在追加时收到错误 在JQ文档中,他们说该方法可以获得JQ对象

<script type="text/javascript">
    $(document).ready(function () {
        var wtf = $(".download");
        var links = $("a", wtf)
        links.each(function (index) {
            var newFrame = document.createElement("div");
            $(newFrame).load($(this).context.href, function (response, status, xhr) {
                if (status == "error") {
                    alert("error");
                }
                $("a", response).each(function (index) {
                    $("#results").append($(this));
                });
            });
            //  $("#results").append(newFrame);
        });
    });
</script>

2 个答案:

答案 0 :(得分:3)

让我们看看我的猜测错误检查能力是否足够好:

// No point really in using context here.
// This would be better, or at least more readable
var links = $(".download a");

// No need to add in the argument if you're not actually going to use it
links.each(function() {
    // Doing this will get you create the jQuery object
    // without having to use the DOM createElement method
    var newFrame = $('<div />');

    // this.href is shorter and neater
    newFrame.load(this.href, {
        'html': '.ajax'
    }, function(response, status, xhr) {
        if (status == "error") {
            console.log(xhr);
        }

        // This is the odd part - response is a selector?
        // This should loop through each anchor that are a child
        // Of the element selected by the response receieved
        // Using appendTo here is better than looping through
        // each element and using .append() there
        $(response).find("a").appendTo("#results");

        // And finally of course because this is .load()
        // Remember that the actual response is also
        // appeneded to the element in question,
        // hence the extra .ajax appearing there
    });

    // This occures outside of callback,
    // so it's actually executed *before* the code above
    $("#results").append(newFrame);
});

请参阅jsfiddle以了解实际工作的这段代码:http://jsfiddle.net/E589q/4/

答案 1 :(得分:0)

load函数没有错误处理功能,仅用于简单的Ajax功能。

试试这个

<script type="text/javascript">
<!--
 $(document).ready(
function () {

    var links = $("a.download")
    $.each(links,
    function () {
        var url = $(this).attr('href');
        var newFrame = $("<div></div>").appendTo('body').css({position: 'absolute', top: '100px',  left: '100px'});
          $(newFrame).load(url)
              })
                            })

//-->
</script>
相关问题