jquery 从 ajax 输出中按 ID 查找 div
恐怕已经有人问过非常类似的问题此处,但由于某种原因它只是输出“null”。
我试图从 id 的 ajax 输出中找到一个 div html。下面是我的脚本。
// LOAD NAVIGATION
$.ajax({
type: 'POST',
url: 'includes/content/bookingsystem/b_navigation.php',
data: thisButtonType + '=true&loadNav=date',
success: function(output) {
alert(output); // Outputs correctly two divs #navDay, and #navMonth
alert($(output).find('#navDay').html()); // Results into "null"
$('#navDay').html($(output).find('#navDay').html()); // Results in an empty div, since it overwrote the html with 'null' - nothing.
//$('#navDay').replaceWith($('#navDay', output)); // Same here - nada.
//$('#navMonth').html($(output).find('#navMonth').html());
}
});
第一个警报(输出)结果如下:
<div id="navDay">Im day nav!</div>
<div id="navMonth">Im month nav!</div>
I'm afraid very similar question has been asked already here, but for some reason it simply outputs "null".
I'm trying to find a div html from an ajax output by id. Below is my script.
// LOAD NAVIGATION
$.ajax({
type: 'POST',
url: 'includes/content/bookingsystem/b_navigation.php',
data: thisButtonType + '=true&loadNav=date',
success: function(output) {
alert(output); // Outputs correctly two divs #navDay, and #navMonth
alert($(output).find('#navDay').html()); // Results into "null"
$('#navDay').html($(output).find('#navDay').html()); // Results in an empty div, since it overwrote the html with 'null' - nothing.
//$('#navDay').replaceWith($('#navDay', output)); // Same here - nada.
//$('#navMonth').html($(output).find('#navMonth').html());
}
});
The first alert(output) results this:
<div id="navDay">Im day nav!</div>
<div id="navMonth">Im month nav!</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您希望能够使用
.find()
或$(selector, context)
,则需要将两个 div 包装在外部 div 中 - 这些函数只能查找 < em>后代节点,并且 HTML 中有两个兄弟节点,没有真正的父节点。您可以在服务器端进行包装,也可以使用
.wrap()
。此外,
.html()
函数仅返回标签的内部内容,而不是标签本身。假设(基于您对
.replaceWith
的使用)您的意图是替换整个元素,而不仅仅是文本,我会选择:此时您之前无法工作的代码中的这一行将也工作:
You need to wrap your two divs in an outer div if you expect to be able to use
.find()
or$(selector, context)
- those functions only find descendent nodes, and you have two sibling nodes in your HTML without a real parent.You could either do that wrapping server side, or use
.wrap()
.Furthermore, the
.html()
function only returns the inner content of your tags, not the tags themselves.Assuming (based on your use of
.replaceWith
) that your intention is to replace entire elements, and not just text, I'd go for:At which point this line from your previously non-working code will work too:
试试这个
Try this