Uncaught TypeError: Cannot read property 'find' of undefined

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);
        });
    }
});

如果您尝试 运行 该代码,它将 return 显示错误。

Uncaught TypeError: Cannot read property 'find' of undefined

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

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 的值在 change() 函数内部不同,以检查您是否可以记录该值。

作为解决方法,您可以保留对它的引用并使用该引用。

您还可以使用 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);
 });

为了补充另一个应该被标记为正确的响应,可以通过三种方式定义this

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

  2. 方法调用(例如,a.f())——这是指点左边的对象(有时称为接收对象)。

  3. 新(构造函数)调用 - 这是指新分配的对象。

您的 .change(...) 电话是上面列表中第二个电话的一个例子。 @sabithpocker 的解决方案在更改 this 的值之前保存对 this 的引用。