检测文本是否被 jquery 然后 运行 函数插入到输入字段

Detect if text is being inserted to input field by jquery then run a function

我有一个输入字段被 html 属性设置为只读 readonly 我正在使用 jQuery .html() 方法将文本插入该字段:

<input type="text" id="myField" readonly="readonly" />

现在我有一个函数 myFunction(),我希望在 jQuery 向该字段插入文本时调用它。

要实现您的要求,您可以使用 val() 设置值,然后触发一个 change 事件,您可以将事件处理程序挂接到该事件:

$('button').click(function() {
  $('#myField').val('foo').trigger('change');
});

$('#myField').change(function() {
  console.log('value changed...');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myField" readonly="readonly" />

<button>Set value</button>

希望对您有所帮助...

<input type="text" id="myField" readonly="readonly" value=""/>

<script>
 $('#myField').on('change', function(){
      if($('#myField').val()!=""){
         myFunction();
      }
 });
</script>