我有一个名为#myHiddenField的隐藏字段。
此字段的内容在不同位置以编程方式更改。
我希望有一种方法可以检测到这种变化。除非我在字段中输入内容,否则change事件不会触发,但这是不可能的。
有没有一种jQuery方法来检测字段中的程序性内容更改?
发布于 2010-11-17 08:13:35
您应该能够使用以下命令触发更改事件:
$('#myHiddenField').change();或
$('#myHiddenField').trigger('change');当然,这将需要负责更新文件的代码块,以便在完成工作后进行其中一个调用。
发布于 2010-11-17 08:18:15
DOM无法检测事件的程序化引发。实际上我昨天碰到了这个。我不记得我是在哪里读到它的,但解决方案是在jQuery元素上实际调用.trigger()。jQuery Doc
发布于 2017-02-11 05:33:15
情况1:您希望自己以编程方式更改该值,并且只想在该值更改时分派一个事件。
$('#myfield').text('New value');
//$('#myfield').val('New value');
$('#myfield').trigger('change');案例2:
假设您想要检测对不是由您编写的字段的编程更改。所以,你不可能触发'change‘事件。
在这种情况下,使用“”DOMSubtreeModified“”检测对父元素的后代元素的编程更改。“”
示例:
<div id="product-addons-total">
<div id="total_price">200</div>
</div>
$(document).ready(function() {
jQuery('#product-addons-total').on("DOMSubtreeModified",function(){
console.log('content changed');
//tamp_price_change_handler();
});
});现在,如果"total_price“的值以某种方式以编程方式更改,它将触发"DOMSubtreeModified”事件。示例:
jQuery('#total_price').text('300');情况2的警告: DOMSubtreeModified可能会创建无限循环,并极大地降低性能。相反,鼓励使用MutationObserver.
MutationObserver示例:
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});
// Let's configure the observer
var config = { childList: true, subtree:true, attributes: true, characterData: true,
characterDataOldValue: true, attributeOldValue: true };
//Let's get a node.
var target = jQuery('#product-addons-total').get(0);
// Let's pass the target and configuration to the observe function.
observer.observe(target, config); 案例3:
上面的方法可以检测到DOM中的变化。但是,如果您希望以编程方式更改输入字段的值,则不会触发这些事件。在这种情况下,唯一的方法是手动触发一个事件。因此,首先更改输入字段的值,然后手动触发事件。
$('#inputfield').val(456465).trigger('change');
//Now the change event will fire.
$('#inputfield').on('change', function() {
console.log('input filed has been changed');
});https://stackoverflow.com/questions/4200358
复制相似问题