我有以下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);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div"></div>
&#13;
答案 0 :(得分:2)
使用jQuery的prepend()
。它的作用与append()
相同,但在目标的开始标记之后插入参数。
答案 1 :(得分:2)
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>