触发文本框中文本的更改

Trigger the change of text in text box

本文关键字:文本 中文      更新时间:2023-09-26

我无法触发当前场景中的文本更改。

如果我点击按钮,我正在改变文本的内容。那么我怎样才能触发文本的变化,这是由外部事件引起的。例如,在点击一个按钮,我可以在文本框中填写任何文本,能够粘贴文本和使用鼠标和键盘。在所有这些场景和类似的场景中,我也希望事件被触发。

我已经试过了。

$('#text_id').on('change', function () {
    alert('This is not trigged when i changed the text');
});

当文本被更改时,警报应该出现。可能有许多可能的来源来更改文本。

这是我创建的提琴

提前感谢。

这是我更新的小提琴

更新后的提琴- http://jsfiddle.net/upa2A/1/

$(document).ready(function () {
    $(document).on('click', "#button_id", function () {
        $('#text_id').val('TExt changed')
    });
    $(document).on('change', "#text_id", function () {
        alert('This is not trigged when i changed the text');
    });
});

原提琴问题 -

  • 代码必须在$(document).ready()
  • function后缺失()
  • 不正确使用$.on(在http://api.jquery.com/on/上了解更多信息)

根据询问的评论进行编辑 -

更新的小提琴- http://jsfiddle.net/upa2A/4/

$(document).ready(function () {
    $(document).on('click', "#button_id", function () {
        $('#text_id').val('TExt changed').change();
    });
    $(document).on('change', "#text_id", function () {
        alert('This is not trigged when i changed the text');
    });
});

更多的编辑基于评论线程 -

From http://api.jquery.com/change "但对于其他元素类型,事件被延迟,直到元素失去焦点。"

由于,当通过按钮点击改变时,文本框没有聚焦,触发不会自动发生

我在jsfiddle中看到了您的代码。你漏掉了一些括号和分号。否则你的代码写。请检查jquery库代码。

$('#button_id').on('click',function()
               {
                   $('#text_id').val('TExt changed');
               }
              );

$('#text_id').on('change',function() {alert('当我更改文本时没有触发');});

试试下面的代码。但为此你应该使用jQuery。当文本发生变化时,它将引发事件。

$('#text_id').on('input propertychange paste', function() {
    alert('Text Changed');
});

工作小提琴在这里

此事件肯定会在文本更改时引发。如果它对你没有用处,肯定会有人为此感到高兴。

var txtVal = '';
setInterval(function() {
    if ($("#text_id").val() != txtVal) {
        txtVal = $("#text_id").val();
        alert("Text Changed");
    }
}, 10);

工作小提琴在这里