我正在尝试通过 JQuery 修改价格。当我将代码添加到控制台时,一切似乎都正常,但 html 没有改变。另外,当我调用 console.log(newPrc)
时,它显示“newPrc”未定义。我的代码是:
(function($) {
Number.prototype.formatMoney = function(c, d, t) {
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
$(document).ready(function() {
oldPrc = jQuery('body.checkout-delivery .basket__totals #grand-total-price .price').html();
newPrc = oldPrc.replace('<span class="currency">£</span>', '');
newPrc = newPrc.split(',');
newPrc = newPrc[0] + newPrc[1];
newPrc = parseInt(newPrc) + 39;
newPrc = '<span class="currency mtI">£</span>' + newPrc;
jQuery('body.checkout-delivery .basket__totals #grand-total-price .price:has(.currency:not(.mtI))').html(newPrc);
});
})(jQuery);
最佳答案
一旦我将 jQuery 和适当的演示标记添加到代码片段中,它似乎会按照您的预期将 39 添加到原始价格(实际上不是,因为 39 加 4.99 不是 43),并在 HTML 中显示结果:
(function($) {
Number.prototype.formatMoney = function(c, d, t) {
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
$(document).ready(function() {
oldPrc = jQuery('body.checkout-delivery .basket__totals #grand-total-price .price').html();
newPrc = oldPrc.replace('<span class="currency">£</span>', '');
newPrc = newPrc.split(',');
newPrc = newPrc[0] + newPrc[1];
newPrc = parseInt(newPrc) + 39;
newPrc = '<span class="currency mtI">£</span>' + newPrc;
jQuery('body.checkout-delivery .basket__totals #grand-total-price .price:has(.currency:not(.mtI))').html(newPrc);
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="checkout-delivery">
<div class="basket__totals">
<div id="grand-total-price">
<div class="price"><span class="currency">£</span>4.99</div>
</div>
</div>
</body>
您的标记与上面的标记类似吗?
关于javascript - jQuery 没有按预期修改 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36559540/