javascript - jquery 从 ajax 输出中按 ID 查找 div

标签 javascript jquery ajax find

恐怕已经有人问过非常类似的问题 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/

相关文章:

javascript - 在 Laravel 中使用 Ajax 时出现 500 Internal Server Error

javascript - 语义 UI 表单 onSuccess 事件未触发

javascript - 使用 $.each jquery 在 ajax 成功中创建 html 选择选项

javascript - Jquery querySelectorAll 使用类以外的其他属性

javascript - react native : Access Component state inside a static function

JavaScript:使用条件语句进行解构

php - "Time ago"来自 MySQL 时间戳

javascript - ExtJS - 应用 JQUEry UI 主题

javascript - 将数据推送到没有索引的数组

javascript - 将最大高度设置为动态表格不起作用?