使用Curry jQuery插件进行货币转换。我使用jscookie将所选货币存储在cookie中。一切都很完美,但是当重新加载页面时,HTML元素不会随所选的选项值而改变。它只会在我手动点击它时发生变化。
↠↠ HERE' S DEMO
以下是curry.js的修改版
/*!
* Curry currency conversion jQuery Plugin v0.8.1
* https://bitbucket.org/netyou/curry-currency-ddm
*
* Copyright 2015, NetYou
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://www.opensource.org/licenses/mit-license.php
* http://www.opensource.org/licenses/GPL-2.0
*/
(function ($) {
var qc;
$.fn.curry = function (options) {
// Setup a global cache for other curry plugins
if (!window.jQCurryPluginCache)
window.jQCurryPluginCache = [{}, false];
var output = '',
rates = {},
t = this,
requestedCurrency = window.jQCurryPluginCache[1],
$document = $(document),
dropDownMenu,
item, keyName,
i, l, rate;
// Create some defaults, extending them with any options that were provided
var settings = $.extend({
target: '.price',
change: true,
base: 'USD',
symbols: {}
}, options);
this.each(function () {
var $this = $(this),
id = $this.attr('id'),
classes = $this.attr('class'),
attrs = '',
tempHolder;
// Add class or id if replaced element had either of them
attrs += id ? ' id="' + id + '"' : '';
if (classes) {
attrs += ' class="curry-ddm"';
if (classes)
attrs += ' ' + classes + '"';
else
attrs += '"';
} else {
attrs += '';
}
// keep any classes attached to the original element
output = '<select' + attrs + '></select>';
// Replace element with generated select
tempHolder = $(output).insertAfter($this);
$this.detach();
// Add new drop down to jquery list (jquery object)
dropDownMenu = !dropDownMenu ? tempHolder : dropDownMenu.add(tempHolder);
});
// Create the html for the drop down menu
var generateDDM = function (rates) {
output = '';
// Change all target elements to drop downs
dropDownMenu.each(function () {
for (i in rates) {
rate = rates[i];
if (i == savedCurrency) {
output += '<option value="' + i + '" data-rate="' + rate + '" selected="selected">' + i + '</option>';
} else {
output += '<option value="' + i + '" data-rate="' + rate + '">' + i + '</option>';
}
}
$(output).appendTo(this);
});
};
if (!settings.customCurrency) {
// Only get currency hash once
if (!requestedCurrency) {
// Request currencies from yahoo finance
var jqxhr = $.ajax({
url: 'https://query.yahooapis.com/v1/public/yql',
dataType: 'jsonp',
data: {
q: 'select * from yahoo.finance.xchange where pair="USDINR,USDEUR,USDCAD,USDGBP,USDILS"',
format: 'json',
env: 'store://datatables.org/alltableswithkeys'
}
});
// Set flag so we know we made a request
window.jQCurryPluginCache[1] = true;
jqxhr
.done(function (data) {
var items = data.query.results.rate;
// Add the base currency to the rates
rates[settings.base] = 1;
for (var i = 0, l = items.length; i < l; i++) {
item = items[i];
keyName = item.Name.substr(item.Name.length - 3);
rates[keyName] = +item.Rate;
}
generateDDM(rates);
window.jQCurryPluginCache[0] = rates;
$document.trigger('jQCurryPlugin.gotRates');
})
.fail(function (err) {
console.log(err);
});
} else {
$document.on('jQCurryPlugin.gotRates', function () {
generateDDM(window.jQCurryPluginCache[0]);
});
}
} else {
generateDDM(settings.customCurrency);
}
// only change target when change is set by user
if (settings.change) {
// Add default currency symbols
var symbols = $.extend({
'USD': '$',
'GBP': '£',
'EUR': '€',
'JPY': '¥'
}, settings.symbols),
$priceTag, symbol;
$document.on('change', this.selector, function () {//alert();
var $target = $(settings.target),
$option = $(this).find(':selected'),
//$option = $(this).attr('selected'),
rate = $option.data('rate'),
has_comma = false,
money, result, l = $target.length;
for (var i = 0; i < l; i++) {
$price = $($target[i]);
money = $price.text();
// Check if field has comma instead of decimal and replace with decimal
if (money.indexOf(',') !== -1) {
has_comma = true;
money = money.replace(',', '.');
}
// Remove anything but the numbers and decimals and convert string to Number
money = Number(money.replace(/[^0-9\.]+/g, ''));
if ($price.data('base-figure')) {
// If the client changed the currency there should be a base stored on the element
result = rate * $price.data('base-figure');
} else {
// Store the base price on the element
$price.data('base-figure', money);
result = rate * money;
}
// Parse as two decimal number with .
result = Number(result.toString().match(/^\d+(?:\.\d{0,2})?/));
// Replace decimal with comma after calculations
if (has_comma) {
result = result.toString().replace('.', ',');
has_comma = false;
}
symbol = symbols[$option.val()] || $option.val();
$price.html('<span class="symbol">' + symbol + '</span>' + result);
}
});
//////
}
// $('#body').ready(function () {
// setTimeout(function () {
// qwe();
// }, 1000);
// });
qc = function qwe() {
var $target = $(settings.target),
//$option = $(this).find(':selected'),
//$option = $(this).attr('selected'),
$option = $('#curry-ddm option[selected="selected"]'),
rate = $option.data('rate'),
has_comma = false,
money, result, l = $target.length;
for (var i = 0; i < l; i++) {
$price = $($target[i]);
money = $price.text();
// Check if field has comma instead of decimal and replace with decimal
if (money.indexOf(',') !== -1) {
has_comma = true;
money = money.replace(',', '.');
}
// Remove anything but the numbers and decimals and convert string to Number
money = Number(money.replace(/[^0-9\.]+/g, ''));
if ($price.data('base-figure')) {
// If the client changed the currency there should be a base stored on the element
result = rate * $price.data('base-figure');
} else {
// Store the base price on the element
$price.data('base-figure', money);
result = rate * money;
}
// Parse as two decimal number with .
result = Number(result.toString().match(/^\d+(?:\.\d{0,2})?/));
// Replace decimal with comma after calculations
if (has_comma) {
result = result.toString().replace('.', ',');
has_comma = false;
}
symbol = symbols[$option.val()] || $option.val();
$price.html('<span class="symbol">' + symbol + '</span>' + result);
}
}
// Returns jQuery object for chaining
return dropDownMenu;
};
// function asd(){
// alert('lkk')
// }
})(jQuery);
jQuery(document).ready(function() {
Custom-prices.js //这会显示自定义选项值
var savedRate, savedCurrency;
var selectElement = '#curry-ddm'; //selected id or class of curry
var targetf = '.edd_price, .edd_price_option_price, .edd-cart-item-price, .cart-total, td.edd_cart_item_price, span.edd_cart_amount';
var options = {
target: targetf,
change: true,
base: savedCurrency,
symbols: {
'USD' : '$ ',
'GBP' : '£ ',
'INR' : '₹ ',
'ILS' : '₪ ',
'CAD' : 'C$ ',
'EUR' : '€ ',
}};
jQuery(function(){
jQuery( selectElement ).curry( options ).change(function(){
var selected = jQuery(this).find(':selected'), // get selected currency
rate = selected.data('rate'), // get currency rate
currency = selected.val(); // get currency name
Cookies.remove('site_currency', { path: '/' });
Cookies.remove('site_rate', { path: '/' });
Cookies.set('site_currency', currency, { expires: 7, path: '/' });
Cookies.set('site_rate', rate, { expires: 7, path: '/' });
console.log( currency, rate );
});
});
jQuery(document).ready(function() {
var CookieSet = Cookies.get('site_currency');
if (typeof CookieSet === "undefined") {
savedRate = 1;
savedCurrency = 'USD';
console.log('CookieSet Empty. Set to '+savedCurrency);
}
else {
savedRate = Cookies.get('site_rate');
savedCurrency = Cookies.get('site_currency');
console.log('CookieSet read from cookie. Saved Rate: '+savedRate+' Saved currency: '+savedCurrency);
}
jQuery( selectElement ).val( savedCurrency );
});
答案 0 :(得分:0)
在你的
中jQuery(document).ready(function() {
如果未定义cookie,则设置变量
if (typeof CookieSet === "undefined") {
你需要添加:
Cookies.set('site_currency', savedCurrency, { expires: 7, path: '/' });
Cookies.set('site_rate', savedRate, { expires: 7, path: '/' });