Pri*_*ERO 3 javascript jquery jquery-plugins jquery-events
我有一个插件,应该在更新"选择器"的值时触发.在正常的UI交互过程中,它就像一个冠军.但是,如果通过JavaScript或jQuery更新"选择器",则不会触发.
插件的一般想法是自动舍入网格和面板等内容.
任何帮助都会很棒......我一整天都在努力!
给出以下HTML:
<input id="myDecimalTotal" type="text" value="0.00" class="rounder-decimal" />
<input id="btnDecimalTotalTest" type="button" value="Run Total" />
Run Code Online (Sandbox Code Playgroud)
使用以下选择器和JavaScript进行测试:
jQuery(document).ready(function() {
jQuery('input.rounder-decimal').numericRounder();
jQuery('#btnDecimalTotalTest').click(overwriteDecimalTotal); // fails
jQuery('#myDecimalTotal').val(777); // fails
});
function overwriteDecimalTotal() {
jQuery('#myDecimalTotal').val(123);
}
Run Code Online (Sandbox Code Playgroud)
对于以下插件:
(function($) {
$.fn.numericRounder = function(options) {
switch (typeof (options)) {
case 'object':
options = $.extend({}, $.fn.numericRounder.defaults, options);
break;
case 'string':
options = $.extend({}, $.fn.numericRounder.defaults, { onEvent: options });
break;
default:
options = $.fn.numericRounder.defaults;
}
return this.each(function() {
var element = $(this);
if (element.is('input.rounder-decimal')) {
switch (options.onEvent) {
case 'change':
element.change(roundDecimal);
break;
case 'blur':
element.blur(roundDecimal);
break;
case 'click':
element.click(roundDecimal);
break;
default:
element.blur(roundDecimal);
}
}
if (element.is('input.rounder-wholeNumber')) {
switch (options.onEvent) {
case 'change':
element.change(function() { roundWholeNumber(this, options.factorOf); });
break;
case 'blur':
element.blur(function() { roundWholeNumber(this, options.factorOf); });
break;
case 'click':
element.click(function() { roundWholeNumber(this, options.factorOf); });
break;
default:
element.blur(function() { roundWholeNumber(this, options.factorOf); });
}
}
/// <summary>Rounds a numeric value to the nearest place.</summary>
function roundDecimal() {
var value = $(this).val();
value = extractValue(value);
if (isNaN(value))
value = $(this).val();
else
value = Math.round(value).toFixed(2);
$(this).val(value);
}
/// <summary>Rounds a numeric value to the nearest place.</summary>
function roundWholeNumber(element, factorOf) {
var value = $(element).val();
value = extractValue(value);
if (isNaN(value))
value = $(element).val();
else
value = Math.round(value / factorOf) * factorOf;
$(element).val(value);
}
/// <summary>Extracts the number.</summary>
function extractValue(value) {
var numericRegEx = /([\d\.])/g;
try {
return value.match(numericRegEx).join('');
}
catch (error) {
return value;
}
}
});
};
/// <summary>Default options.</summary>
$.fn.numericRounder.defaults = { onEvent: 'change', factorOf: 10 };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
据我所知,这就是它的方式.change从JavaScript更改值时不会触发该事件.得到它很容易(使用jQuery):
jQuery('#myDecimalTotal').val(123).change();
Run Code Online (Sandbox Code Playgroud)
这将触发change该元素上的所有事件处理程序.
| 归档时间: |
|
| 查看次数: |
2440 次 |
| 最近记录: |