【问题标题】:jQuery onchange detectionjQuery onchange 检测
【发布时间】:2011-03-18 08:15:58
【问题描述】:

我想执行 html 元素的“onchange”属性中的 javascript。所以..

<input id="el" type="text" onchange="alert('test');" value="" />

使用该示例,我想通过 jQuery 执行 alert('test'); 部分,问题是.change() 事件处理程序不起作用,因为我想在另一个元素更改它的值后执行它。所以..

$('#el').val('test');

这是我想执行 onchange 的时候。之后 .val val 已被调用。有什么想法吗?

【问题讨论】:

  • 您能否添加更多关于您正在谈论的元素或代码的描述? the first element, which has an onchange attributethe other element 更容易阅读。
  • 避免使用内联 JavaScript。使用jQuery附加change handler,管理起来会更方便。

标签: javascript jquery onchange


【解决方案1】:

.val() 不会触发 change 事件。您需要自己手动操作。例如:

$('#el').val('test').change();

你可以像这样将它封装在一个小的 jQuery 插件中:

(function ($) {
    $.fn.changeVal = function (text) {
        this.val(text).change();
    };
}(jQuery));

$('#el').changeVal('test');

【讨论】:

    【解决方案2】:

    我认为 onchange 事件总是在字段值更改时触发是有道理的。因此,我会更改 JQuery 本身中的 val 函数,而不是创建自定义函数。这样,您不必担心使用哪个函数来设置对象的值,并且如果您已经使用 JQuery 来编写应用程序,则不必更改所有 val 调用。代码如下:

    //Store the old val function
    $.fn.custom_oldVal = $.fn.val;
    
    //Update the val function to fire the change event where appropriate:
    $.fn.val = function(value) {
        if(value == null || value == undefined){
            return this.custom_oldVal();
        } else {
            //Only call onchange if the value has changed
            if(value == this.custom_oldVal()){
                return this;//Return this object for chain processing
            } else {
                return this.custom_oldVal(value).change();
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      前段时间我遇到了同样的问题,但找不到任何好的解决方案。似乎最好的解决方案是对输入进行“拉动”,或者从实际更改输入内容的代码中触发您的 onchange 函数(如 Domenic 节目)。

      【讨论】:

        【解决方案4】:

        如果您先
        input.focus(); 然后$.val('abcd'); 将触发更改事件。
        取自 jquery 站点

        【讨论】:

          【解决方案5】:

          我会重新设计并开始使用 knockout.js 插件,它使用数据绑定,让你可以轻松使用所有绑定。

          示例代码如下:

          var ViewModel = function(first, last) {
          this.firstName = ko.observable(first);
          this.lastName = ko.observable(last);
          
          this.fullName = ko.computed(function() {
              // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
              return this.firstName() + " " + this.lastName();
          }, this);
          

          };

          ko.applyBindings(new ViewModel("Planet", "Earth"));

          【讨论】:

            猜你喜欢
            • 2011-07-05
            • 2011-02-18
            • 2018-06-08
            • 2015-10-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-05-19
            相关资源
            最近更新 更多