javascript - 为什么 .html() 不将所有内容替换为当前值?

标签 javascript jquery html css

这是我的代码:

$('table').html('<tr><td>test</td></tr>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<img src="default.jpg" />
</table>

如您所见,该图像仍然存在。为什么?我用过 .html ,所以这是执行此操作后的预期结果:$('table').html('<tr><td>test</td></tr>');

<table>
    <tr>
        <td>test</td>
    </tr>
</table>

我该怎么做?

最佳答案

原因是 img在您调用 html 时不在表内,因为这是不允许的。 <table><img ...></table>是无效标记;表只能直接包含certain table-related elements , 不是 img元素。因此,浏览器通过移动 img 来为您修复它。离开 table 。 (例如:Chrome 通过将 img 移动到表格正前方来修复它:<img ...><table></table>。)

如果它首先在表中,是的,调用 html替换表格内容会起作用:

$('table').html('<tr><td>test</td></tr>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <img src="default.jpg" />
    </td>
  </tr>
</table>


在您提出的评论中:

...how can I select the image in this? <img src="#" /> <table></table> ? Actually I want to start selecting with table tag. like this $('table').sibiling ...

我不认为你可以,可靠地,因为原始标记再次无效,所以浏览器可以自由地做他们想处理的事情。也就是说,Chrome、Firefox 和 IE11 似乎都将 img 放在了 表格之前,所以 $("selector-for-the-table").prev()应该是 img :

var table = $('table');
table.html('<tr><td>test</td></tr>');
table.prev().remove(); // Remove the img
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<img src="default.jpg" />
</table>

关于javascript - 为什么 .html() 不将所有内容替换为当前值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42467497/

相关文章:

网格中灯光序列的Javascript问题

javascript - 准确的长轮询示例?

jquery - 在 jQuery 中对列表进行排序无法正常工作

html - Div的悬停倾斜

javascript - 单击时如何使用纯 javascript 获取 div 或 anchor 标记的 id

jquery - 具有相同高度的 super 菜单和 div

javascript - 使用 JavaScript 检测是否选择了文本区域内容

javascript - 如何从同一元素中的另一个属性获取一个属性

javascript - 动态创建的元素上的事件绑定(bind)?

javascript - setInterval 在第一次运行时不会触发内部脚本