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

时间:2018-01-30 04:52:13

标签: javascript jquery jconfirm

美好的一天,我正在使用 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);
        });
    }
});

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

  

未捕获的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);
            });

2 个答案:

答案 0 :(得分:2)

为了补充应该标记为正确的其他响应,有三种方法可以定义this

  1. 函数调用(例如,f()) - 这是指全局对象。

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

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

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

答案 1 :(得分:1)

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