在我的Shopify商店中,收藏页上启用了分页。我正在使用jquery脚本更改所有销售标签的文本。该脚本在第一页上执行得很好,但是当我导航到下一页时,我必须调用它,并使用mutationObserver来检测dom的变化。变异观察者执行得很好,但是当我添加用于更改新节点的销售标签的脚本时,它开始递归循环,页面变得无响应。
带有变异观察者的代码是:
var targetNode = document.getElementById('gf-grid');
// Options for the observer (which mutations to observe)
var config = { attributes: false, childList: true, subtree: true };
// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
$('.product-inner').each(function () {
var tag = $(this).find('span.sale');
var oldPrice=$(this).find('.price-old').text();
var ac = oldPrice.replace(/[, ]+/g, "").trim();
var sd=parseInt(ac);
var newPrice = $(this).find('.price-new').text();
var az = newPrice.replace(/[, ]+/g, "").trim();
var gz=parseInt(az);
if (!isNaN(sd)){
var vvv = sd - gz;
var nval = vvv / sd;
var percentOff = Math.round(nval * 100);
$(tag).text(percentOff + "%");
}
});
console.log(oldPrice);
observer.disconnect();
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);