【问题标题】:Jquery Each Function Is Not Working How I ExpectJquery 每个函数都没有按我的预期工作
【发布时间】:2017-02-02 21:39:31
【问题描述】:

我正在尝试在更改事件中更改表值。当.woocommerce-variation 着火时,通过乘以totalvaluefirst 来计算新的比率。然后使用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);
    });
});

【问题讨论】:

  • .bind 已弃用,请改用.on
  • ratio 在哪里定义?此外,您的 JS 不完整,因为您缺少最后一个右括号 });
  • 我缩小了代码,它正在工作,但我的问题(jQuery( this ).text() )每次都是一样的。
  • 你能告诉我们jQuery( ".total-value" ).length是什么吗?
  • 你想做什么?我猜有多个 .woocommerce-variation 元素。您所做的是为每个元素计算不同的值并将其设置为每个元素的新值。这行得通,但你似乎想做一些事情,比如计算账单,这是你想要的吗?

标签: javascript jquery text each dom-manipulation


【解决方案1】:

另见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");

【讨论】:

  • 如何更改dom?更新你的小提琴!
  • 什么意思?我在底部触发了 change DOM 事件。
  • 不,我的意思是选择元素之类的东西,以便 OP 可以检查它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多