简体   繁体   中英

How to call function when ajax content changes?

So i'm working on a shopify site and stuck on a script m writing, the situation is that there is a plugin installed to insert reviews on the site, and the task is to make every user have a "verified buyer" tag just after the user name even if its not a verified user, since the real verified user have a tag through the plugin, the job is to insert it after every user expect those which already have it, I was able to do it using this script -

$(document).ajaxStart(function(){

function addVerified(){

    var list=document.querySelectorAll('display-wrapper .nav-content .reviews-active .review');
    for(let li of list){

        if(!li.classList.contains('hidden')&& (!li.firstElementChild.classList.contains('verified-buyer'))){
            let needElem=li.firstElementChild.children[1].firstElementChild;
            needElem.insertAdjacentHTML('afterend','<div class="label-with-tooltip pull-left">  <span class="y-label>Verified Buyer</span>   </div>'); 

        }
    }
}

addVerified();

});

Everything works right expect when pagination below the reviews is used, the content changes and the reviews changes and the function does not work thus making the verified buyer tag removed, I have tried DOMSubtreeModified (made the script stuck in infinite loop), ajaxComplete to execute the function, but nothing have worked so far, I have not much knowledge of javascript I'm still learning, after getting too frustrated I decided to post it here. Please help

Okay... With the rest of your markup I can suggest something.

That is a lie made to customers... I don't like that.

But anyway, here is the way to tweak on it:

// Create the element to insert
var fake_verified_buyer = $('<div class="label-with-tooltip pull-left">  <span class="y-label yotpo-user-title yotpo-action-hover" data-type="toggleFade" data-target="yotpo-tool-tip">Verified Buyer</span>  <div class="yotpo-tool-tip yotpo-animation-fade" data-user-type="yotpo-verified-buyer"> <div class="tool-tip-header"> <span>What is a</span> <span class="header-green">Verified Buyer</span> </div> <div class="tool-tip-content"> A Verified Buyer is a user who has purchased the reviewed product through our store. </div> </div> </div>');

// On pagination click, insert that element after each user name, if not already present.
$(document).on("click",".yotpo-pager",function(){
  setTimeout(function(){
    $(document).find(".yotpo-user-name").each(function(){
      if(!$(this).next().is(".label-with-tooltip")){

        var clone = fake_verified_buyer.clone();
        clone.insertAfter(this);
      }
    });
  },100);
});

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