简体   繁体   中英

How to update HTML elements in div using jQuery

I'm struggling trying to fix and implement a feature in my project.

In my app each user can upload via AJAX images along data and related infos. Each images is added to a gallery and there are small badges showing which data and info the user has applied in the upload form.

Data and info can be updated using modal form. Below the result of each image in gallery with the small badges: 在此处输入图片说明

Below the code dinamically added by the jQuery script.

<p class="badges" data-badges="${data.pictures[i].imgid}">
${(() => {
  if (data.pictures[i].status == '1'){
    return `<span class="badge badge-success statusBadge">Published</span>`
  } else {
    return `<span class="badge badge-warning statusBadge">Hidden</span>`
  }
})()}
${(() => {
    if (data.pictures[i].infos){
        return `<span class="badge badge-info infoBadge">Info</span>`
    }
    return '';
})()}
${(() => {
    if (data.pictures[i].codes || data.pictures[i].date || data.pictures[i].event ||  data.pictures[i].location){
        return `<span class="badge badge-secondary dataBadge">Data</span>`
    }
    return '';
})()}
${(() => {
    if (data.pictures[i].crid){
        return `<span class="badge badge-primary creditBadge">Credit</span>`
    }
    return '';
})()}
</p>

So, there is a main P tag with class badges and data-badges attribute with a unique id

Now...the issue: I want to update the badges after the first one ( with class statusBadge inside the main p tag) when the user apply new data/info using a modal form.

I'm trying to use the following code to remove and re-create the badges inside the main p tag...but I'm not able to keep the first status badge there...

let badges = $('.badges[data-badges="' + imgid + '"]');
badges.empty();
$.ajax({
    dataType: 'json',
    type:'GET',
    url: `${controller_url}/get_${category}_badges/${imgid}`,
}).done(function(data){
    if(data.status) {
        $(`   
            ${(() => {
                if (data.badges.info){
                    return `<span class="badge badge-info">Info</span>`
                }
                return '';
            })()}
            ${(() => {
                if (data.badges.data){
                    return `<span class="badge badge-secondary">Data</span>`
                }
                return '';
            })()}
            ${(() => {
                if (data.badges.credit){
                    return `<span class="badge badge-primary">Credit</span>`
                }
                return '';
            })()}
         `).appendTo(badges);   
    }
});

Additional, I'm not sure if it's better to use empty() instead remove() to get rid of the badges that need to be updated.

Sorry for the long post, hope I have explained the issue...and...don't blame me! Thanks a lot for any hint and help

I un-knotted your jQuery script. I hope you still find your way around. The top two lines are an attempt of setting up something like an Ajax structure here on SO.

 // this is a "pretend PHP-server", returning a JSON string: const blb=da=>URL.createObjectURL(new Blob([JSON.stringify(da)],{type: "text/json"})); let imgid="img1"; // set some context ... the current imgid let badges = $('.badges[data-badges="' + imgid + '"]'); $.ajax({ dataType: 'json', type:'GET', url: blb({status:1,badges:{info:1,data:2,credit:3}}) // `${controller_url}/get_${category}_badges/${imgid}` }).done(function(data){ if(data.status) { badges.empty().append( Object.keys(data.badges).map(b=>`<span class="badge badge-${b}">${b}</span>`).join("") ) } });
 img {border: 2px grey solid} .badges span {padding:10px;margin:6px; width:30px; background-color:#def;border:1px #07f solid}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container"> <img src="https://i.stack.imgur.com/Zw4w0.jpg" > <div class="badges" data-badges="img1"> initial badges ... </div> </div>

Instead of using separate function calls in the .done() function I go through all the defined keys in the data.badges object and create a badge for each one of them. Obviously, my CSS is more than rudimentary ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM