我在概念上正在努力解决如何实现这一点(绑定(bind)到哪些事件等)。
我正在使用 CakePHP 并具有以下 View :
- 要显示的产品数组和关联价格 ($products['Product']['price'])
- 每个产品都有一个基础货币集 ($product['Currency]['currency'])
- 我有 Money.js、accounting.js 和另一个为 fx.rates 和 fx.base 设置 JSON 数据的 JS
- 我知道用户想要查看的货币,并且可能与产品基础货币不同 (SessionComponent::read('User.Preferences.Currency')
- 用于显示货币简称 (USD) 和换算值的 div,每个 div 都有唯一的 ID
我的简单测试工作正常 - 使用 inline-php 我在页面上的两个脚本标记之间放置了一些 JS。
<script>
var value = accounting.unformat(<? echo $product['Product']['price'] ?>); // clean up number (eg. user input)
var target = "<? echo SessionComponent::read('User.Preference.currency'); ?>"; // or some user input
var convertedValue = fx(value).from("<? echo $product['Currency']['currency'] >").to(target);
accounting.formatMoney(convertedValue, {
symbol: target,
format: "%v %s"
}); // eg. "53,180.08 GBP"
alert(convertedValue);
</script>
好吧。效果很好。但我不知道如何在包含 N 个产品的页面上实现这一点。
我假设我创建了一个 JS 函数,例如:
fx_convert(divid, price, fromcurrency, tocurrency)
在我的 Cake View 中,我使用内联 php 来回显函数参数。
使用 jQuery 实现此功能并让价格“div”调用 fx_convert 并使用转换后的值更新其内容的简洁方法是什么?
或者我的想法完全落后了?非常感谢所有帮助。
最佳答案
睡了一觉后,我想通了。 :)
使用内联 PHP,我通过 div 属性传递货币,并设置统一的类名。例如
<div class="fx" fx-from="<?php echo $product['Currency']['currency']; ?>" fx-to="<?php echo SessionComponent::read('User.Preference.currency') ?>" fx-value="<?php echo $product['Product']['price']; ?>"></div>
然后使用下面的 jQuery 代码片段循环遍历“fx”类的所有元素并进行所需的计算(使用优秀的 Money.js 和accounting.js)
$(document).ready(function() {
$(".fx").each( function( index, element ){
var value = accounting.unformat($(this).attr("fx-value")); // clean up number (eg. user input)
var target = $(this).attr("fx-to"); // or some user input
var convertedValue = fx(value).from($(this).attr("fx-from")).to(target);
$(this).html(accounting.formatMoney(convertedValue, {
symbol: target,
format: "%v %s"
}));
});
});
仍然需要重构和整理,但解决方案已经有了。
关于php - 在同一页面的多个字段上实现money.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15721322/