javascript - jQuery 仅当 div 不为空时才追加

标签 javascript jquery html

我有一个 div 元素,我想在悬停时向其附加一个图标,但只有当 div 不为空时 jQuery 才会附加图标,否则什么也不会发生。

$('div #tags').hover(function() {
  $(this).append('<p>+</p>')
}, function() {
  $(this).find("p").last().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tags">
  <p>The div isn't empty</p>
</div>

最佳答案

由于 divid 引用相同的元素,因此选择器中不应在它们之间有任何空格。

请注意:id属性在文档中是唯一的,只需 $('#tags') 就足以安全地定位该元素。

$('#tags').hover(function() {
  $(this).append('<i class="fa fa-plus-circle ml-1 add-tag-icon"></i>')
}, function() {
  $(this).find("i").last().remove();
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tags">
    <p>The div isn't empty</p>
</div>

只有当 div 不为空时,jQuery 才会附加图标,否则什么也不会发生。

如果 div 为空,则页面中没有任何内容可供您悬停。请参阅以下示例:

$('#tags').hover(function() {
  $(this).append('<p>+</p>')
}, function() {
  $(this).find("p").last().remove();
});
#tags{
  width: 100px;
  height: 15px;
  background-color: lightgray;
  border: 1px solid gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tags">
  
</div>

关于javascript - jQuery 仅当 div 不为空时才追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58609246/

相关文章:

javascript - 将数字列表转换为代码

jquery - 无法使用 jQuery 加载 JSON 上的完整数据

jquery - 使用 jquery AJAX 和 FormData 上传文件

javascript - Jquery-Mobile:将数据附加到非 native 选择选项菜单

html - CSS:背面可见性不起作用?

javascript - Service Worker 注册错误 : Unsupported MIME type ('text/html' )

javascript 大数组或对象 : browser performance and memory

javascript - 如何在纯JS中的一行后插入一组表行

javascript - 用于获取正在单击的按钮附近的 'a' 标签的 href 的 jquery 代码

python - flask 如何传递 2 个参数?