可能重複:
jQuery textbox.val('xxxx') not causing change to fire?爲什麼不在selector.val(1234)上觸發change事件?
我有一個插件,當出現一個「選擇」的值更新爲火。在正常的UI交互過程中,它就像一個冠軍。但是,如果通過JavaScript或jQuery更新「選擇器」,則不會觸發它。
- 更新直接通過文本框...... 它的工作原理。
- 按下按鈕... 失敗。
- 使用jQuery調用select.val(xxx)更新... 它失敗。
了插件的總體思路是:全面自動彙總等東西網格和麪板等
任何幫助將是巨大的......我這個整天一直在努力!
給出下面的HTML:
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);
}
對於以下插件:
使用下面的選擇器(S)和JavaScript
<input id="myDecimalTotal" type="text" value="0.00" class="rounder-decimal" />
<input id="btnDecimalTotalTest" type="button" value="Run Total" />
測試
(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);
非常感謝你 – 2011-03-24 20:41:03