jQuery检测到字段的程序变化

gri*_*egs 26 jquery

我有一个名为#myHiddenFieldsay 的隐藏字段.

该字段的内容在各个地方以编程方式改变.

我想要一种检测变化的方法.除非我输入字段,否则更改事件不会触发,但这是不可能的.

是否有jQuery方法来检测字段中的程序化内容更改?

pro*_*son 28

您应该能够通过以下方式触发更改事件:

$('#myHiddenField').change();
Run Code Online (Sandbox Code Playgroud)

要么

$('#myHiddenField').trigger('change');
Run Code Online (Sandbox Code Playgroud)

当然,这需要负责更新字段的代码块,以便在完成其工作后进行其中一个调用.


pin*_*x33 6

DOM无法检测到事件的程序化提升.我昨天碰到了这个.我不记得我在哪里阅读它,但解决方案是实际调用.trigger()jQuery元素.jQuery Doc


Md.*_*med 6

情况 1: 您想要自己以编程方式更改该值,并且只想在该值更改时调度一个事件。

$('#myfield').text('New value');
//$('#myfield').val('New value');
$('#myfield').trigger('change');
Run Code Online (Sandbox Code Playgroud)

案例2:

假设您想要检测对不是您编写的字段的编程更改。因此,您无法触发“更改”事件。

在这种情况下,使用“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();
    });
});
Run Code Online (Sandbox Code Playgroud)

现在,如果“total_price”的值以某种方式以编程方式发生变化,它将触发“DOMSubtreeModified”事件。例子:

jQuery('#total_price').text('300');
Run Code Online (Sandbox Code Playgroud)

注意情况 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); 
Run Code Online (Sandbox Code Playgroud)

案例3:

上述方式可以检测DOM的变化。但如果您想以编程方式更改输入字段的值,那么这些事件将不会触发。这种情况下,唯一的办法就是手动触发事件。因此,首先更改输入字段的值,然后手动触发事件。

$('#inputfield').val(456465).trigger('change');

//Now the change event will fire.
$('#inputfield').on('change', function() {  
    console.log('input filed has been changed');
});
Run Code Online (Sandbox Code Playgroud)