gpt4 book ai didi

javascript - 在内部文本之前插入子元素

转载 作者:行者123 更新时间:2023-11-28 15:06:07 25 4
gpt4 key购买 nike

我有以下 jQuery/JavaScript 代码。它向现有的 <div> 添加了几个元素。它工作正常,只是我希望将文本插入到第一个图像之后。

jQuery 是否提供了简单的语法来添加子项 <img>内部文本之前的元素?我知道我可以单独创建元素,但我希望表达式尽可能简单。

var div = document.getElementById("div");

var attachmentDiv = $('<div />', { 'class': 'Attachment' });
attachmentDiv.append($('<a />', { href: '#', title: 'Download Attachment', text: 'Filename.ext' })
.append($('<img />', { src: 'https://cdn0.iconfinder.com/data/icons/typicons-2/24/spanner-128.png', 'class': 'AttachmentIcon', alt: 'File Attachment' })));
attachmentDiv.append($('<a />', { href: '#', title: 'Delete Attachment', 'data-id': '000' })
.append($('<img />', { src: 'https://cdn0.iconfinder.com/data/icons/typicons-2/24/spanner-128.png', 'class': 'AttachmentDeleteIcon', alt: 'Delete Attachment' })));
$(div).append(attachmentDiv);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div"></div>

最佳答案

var div = document.getElementById("div");

var attachmentDiv = $('<div />', { 'class': 'Attachment' });
attachmentDiv.append($('<a />', { href: '#', title: 'Download Attachment', text: 'Filename.ext' })
.prepend($('<img />', { src: 'https://cdn0.iconfinder.com/data/icons/typicons-2/24/spanner-128.png', 'class': 'AttachmentIcon', alt: 'File Attachment' })));
attachmentDiv.append($('<a />', { href: '#', title: 'Delete Attachment', 'data-id': '000' })
.append($('<img />', { src: 'https://cdn0.iconfinder.com/data/icons/typicons-2/24/spanner-128.png', 'class': 'AttachmentDeleteIcon', alt: 'Delete Attachment' })));
$(div).append(attachmentDiv);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div"></div>

关于javascript - 在内部文本之前插入子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38840106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com