[英]Jquery Each Function Is Not Working How I Expect
我正在嘗試在change事件上更改表值。 當.woocommerce-variation
觸發時,新比率是通過將totalvaluefirst
乘以py來計算的。 然后使用totalvaluelast
設置文本。 但是,當觸發第二個事件時, totalvaluefirst
保持不變,並且文本不會更改。
jQuery('.woocommerce-variation').bind("DOMSubtreeModified",function(){
jQuery( ".total-value" ).each(function() {
var totalvaluefirst = (jQuery( this ).text() );
var totalvaluefirstnew = ratio * totalvaluefirst;
var totalvaluelast = Math.round( totalvaluelast * Math.pow(10, 2) ) / Math.pow(10, 2);
jQuery( this ).text(totalvaluelast);
});
});
另請參閱https://jsfiddle.net/ngfkqbvt/
我添加了一個保護措施:當您通過更改總值來修改dom時,它不應導致重復處理DOM事件。
HTML:
<div class="woocommerce-variation">
<div class="row">1
<div class="single-value">
11
</div>
<div class="total-value">
</div>
<div class="row">2
<div class="single-value">
20
</div>
<div class="total-value">
</div>
</div>
</div>
JavaScript的:
var ratio = 3.0;
var modifyingDOM = false;
jQuery('.woocommerce-variation').bind("DOMSubtreeModified",function(){
if(modifyingDOM)
return;
modifyingDOM = true;
jQuery(this).find( ".row" ).each(function() {
var totalvaluefirst = parseInt(jQuery( this ).find(".single-value").text() );
var totalvaluefirstnew = ratio * totalvaluefirst;
var totalvaluelast = Math.round( totalvaluefirstnew * Math.pow(10, 2) ) / Math.pow(10, 2);
jQuery( this ).find(".total-value").text(totalvaluelast);
});
modifyingDOM = false;
});
//change the DOM
jQuery('.woocommerce-variation').trigger("DOMSubtreeModified");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.