Jquery 将属性传递给带有子元素的自闭元素

Jquery pass attributes to a self-closed element with sub-elements

我想将属性传递给自闭元素。但是,它应该包含一个 子元素

例如 <a>href=" variable-1" 以及 子元素 <img>src="variable-2" and class="variable-3"

我想在属性中包含来自 Firebase 实时数据库 的数据。

var Gallery = firebase.database().ref().child("Gallery");


 Gallery.on("child_added", snap => {

     var img = snap.child("IMG").val();
     var link = snap.child("Link").val();
     var tag = snap.child("Tag").val();

     $("#Gallery").each(function () {
         $('<a>', {
             'href': link,
             appendTo: this
         });
     });
 });

希望有人能帮助我:)

更新:
我找到了适合我的解决方案:

var GalleryWrap = document.getElementById("GalleryWrap");
 var Gallery = firebase.database().ref().child("Gallery");


 Gallery.on("child_added", snap => {

     var img = snap.child("IMG").val();
     var link = snap.child("Link").val();
     var tag = snap.child("Tags").val();
     var title = snap.child("Title").val();

     $("#GalleryWrap").each(function () {

         var LinkRef = document.createElement("a");
         LinkRef.setAttribute('href', link);


         var ImageBoxContainer = document.createElement("div");
         ImageBoxContainer.setAttribute('class', "imagecontainer " + tag);


         var ImageTitle = document.createElement("div");
         ImageTitle.setAttribute('class', "ImageTitle ");


         var Image = document.createElement("img");
         Image.setAttribute('src', img);
         Image.setAttribute('class', "imageboxes");


         GalleryWrap.appendChild(LinkRef);
         LinkRef.appendChild(ImageBoxContainer);
         ImageBoxContainer.appendChild(ImageTitle);

         ImageBoxContainer.appendChild(Image);
         ImageTitle.append(title);

     });
 });

您可以轻松地提供和稍后访问数据集值,如下所述

const RTDB_DATA = {
 userName: 'Joe',
 userSurname: 'Black'
}

$("#Gallery").each(function () {
     $('<div>', 
     {
         href: 'https://whosebug.com/',
         text: `${RTDB_DATA.userName} ${RTDB_DATA.userSurname}`,
         appendTo: this,
         'data-user-name': RTDB_DATA.userName,
         'data-user-surname': RTDB_DATA.userSurname
     }).on('click', function () {
       console.log(this.dataset)
       console.log(this.dataset.userName)
       console.log(this.dataset.userSurname)
     })
});
#Gallery > div {
  text-decoration: underline;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Gallery">
Please click on the user name to see the results:
</div>