恐怕已经有人问过非常类似的问题 here ,但由于某种原因它只是输出“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>
最佳答案
如果您希望能够使用 .find()
或 $(selector, context)
- 这些函数,您需要将两个 div 包装在外部 div 中只找到后代节点,并且 HTML 中有两个兄弟节点,没有真正的父节点。
您可以在服务器端进行包装,或者使用 .wrap()
。
此外,.html()
函数仅返回标签的内部内容,而不是标签本身。
假设(基于您对 .replaceWith
的使用)您的意图是替换整个元素,而不仅仅是文本,我会选择:
<div>
<div id="navDay">Im day nav!</div>
<div id="navMonth">Im month nav!</div>
</div>
此时,您之前无法工作的代码中的这一行也将起作用:
$('#navDay').replaceWith($('#navDay', output));
关于javascript - jquery 从 ajax 输出中按 ID 查找 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6902791/