繁体   English   中英

Uncaught TypeError:无法读取未定义的属性“ find”

[英]Uncaught TypeError: Cannot read property 'find' of undefined

美好的一天,我在网站项目中使用了jconfirm ,但遇到了一个我自己无法解决的怪异问题,请参见下面的代码。

$.confirm({
    title: 'Add Patient',
   theme: 'material',
    backgroundDismissAnimation: 'glow',
    type:'blue',
    typeAnimated: true,
    content: '' +
    '<form action="" class="formName" style ="margin: 10px;">' +
    '<div class="form-group">' +
    '<label>ID NUMBER</label>' +
    '<input type="text" class="id_number form-control" value="my id" required />' +
    '</div>' +
    '</form>',
    buttons: {
        formSubmit: {
            text: 'Submit',
            btnClass: 'btn-blue',
            action: function () {
            }
        },
        cancel: function () {
            //close
        },
    },
    onContentReady: function () {
        this.$content.find('.id_number').change(function(){
            var a = this.$content.find('.id_number').val();
             alert(a);
        });
    }
});

如果您尝试运行该代码,则会返回错误提示。

Uncaught TypeError:无法读取未定义的属性“ find”

但是奇怪的是,如果我像这样更改代码。

onContentReady: function () {
                var a = this.$content.find('.id_number').val();
                 alert(a);
        }

错误消失了,并且警报弹出。

我的问题是如何在change()方法中获取输入的值? 请提供帮助,或者使该代码正常工作的正确方法是什么?

onContentReady: function () {
            this.$content.find('.id_number').change(function(){
                var a = this.$content.find('.id_number').val();
                 alert(a);
            });

为了补充应被标记为正确的其他响应,可以使用三种方法来定义this响应。

  1. 函数调用(例如f())-引用全局对象。

  2. 方法调用(例如,af())-这是指点左侧的对象(有时称为接收对象)。

  3. 新建(构造函数)调用-引用新分配的对象。

您的.change(...)调用是上面列表中第二个示例。 @ sabithpocker的解决方案节省了参考this前值this改变。

change()函数中, this值不同,以检查是否可以记录该值。

解决方法是,可以保留对此的引用并使用该引用。

您还可以使用bind()this的值绑定到事件处理程序。 或使用call()apply检查其他不同方式。

onContentReady: function() {
    var myReferenceToThis = this;
    this.$content.find('.id_number').change(function() {
      var a = myReferenceToThis.$content.find('.id_number').val();
      alert(a);
});

或者就您而言,如@Phil所建议的,只需...

onContentReady: function() {
    var myReferenceToThis = this;
    this.$content.find('.id_number').change(function() {
      var a = $(this).val();
      alert(a);
 });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM