开发者

Objects I add with jQuery are not displaying?

I am new to jQuery, and I am trying to add new elements to an existing div

My jQuery:

function开发者_JS百科 GetXML1Response(results) {
        $(results).filter("Child").each(function () {
            var newDiv = $("<div>").text("Value: " + $(this).attr("value"));
            $("#contentDiv").append(newDiv);
        });
    }

My HTML:

<div id="contentDiv">
        <div>TEST 1</div>
    </div>

If I look at it in the debugger, it adds the new divs as expected, but they do not appear, and on the next call, they have disappeared.

Any help is appreciated.

EDIT:

I think I may know where the problem is coming from. This function is triggered as the callback to a WebMethod. I suspect that it may be happening on a different thread, and thus the changes made are being lost?


Because the Child nodes are nested, you should use the find()[docs] method or the children()[docs] method instead of the filter()[docs] method .

$(results).find("Child").each(...  // searches all descendants

or

$(results).children("Child").each(... // searches only immediate descendants


You're using .filter incorrectly, you want .find:

function GetXML1Response(results) {
    $(results).find("Child").each(function () {
        var newDiv = $("<div>").text("Value: " + $(this).attr("value"));
        $("#contentDiv").append(newDiv);
    });
}

You're handing .filter a single <rootElement> and asking it filter out everything that isn't <Child>, the result is an empty list. If you do the same with .find then you will be giving .find <rootElement> and you're asking it to extract all the <Child> elements that it contains (and this is what you want to happen).


Well, I figured it out. Not jQuery at all. I had an HTML Button, and it was automatically doing a postback. When I added

return false;

after the function call, it worked as expected.

Thank you all for your help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜