jQuery find返回空字符串

jQuery find returns empty string

本文关键字:字符串 返回 find jQuery      更新时间:2023-09-26

我正在做ajax POST,当它成功时,我想用成功的ajax中的div替换当前的div:

var dom;
var target;
$.ajax({
    type: "POST",
    url: "http://127.0.0.1/participants",   
    data: "action=addparticipant&userid=1",
    success: function (html) {
        dom = $.parseHTML(html);
        target = $(dom).find("#listParticipants").val();
        $('#listParticipants').html(target);                
    }
});

target似乎是空的…

,当我使用firebug调试时,dom是:

[<TextNode textContent="'n'n">, <TextNode textContent="'n'n">,
div#listParticipants, <TextNode textContent="'n 'n 'n">,
<TextNode textContent="'n'n">, <TextNode textContent="'n'n">]
谁能帮我解决这个问题?

您应该使用$.filter(),而不是$.find

target = $(dom).filter("#listParticipants").html()

正如Juan指出的,您需要的是innerHTML,而不是value。

需要使用filter的原因是您的控制台显示的是节点数组,而不是单个DOM元素。这意味着您需要过滤该集合。

$().val()方法用于输入字段。见http://api.jquery.com/val/

也正如epascarello https://stackoverflow.com/a/25142313/227299指出的那样,您有一组节点,因此您需要$.filter,而不是$.find

如果你想要innerHTML,使用$(dom).filter("#listParticipants").html()