2012-12-06 18 views
1

我正在使用jQuery v1.8.3和jQuery UI v1.9.2。我已经实现了Autocomplete部件是这样的:为什么jQuery.data的行为与jQuery UI options-events不同?

$('#input_id').autocomplete({ 
    create: function (event, ui) { 
    // Initialize data 
    $(this).data('custom', { property1: 'Hello', property2: { num: 1, funct: function() { ... return value } }); 

    alert($(this).data('custom').property1) // Display 'Hello' 
    }, 

    select: function(event, ui) { 
    alert($(this).data('custom').property1) // Display 'Hello' 
    }, 

    source: function(request, response) { 
    alert($(this).data('custom').property1) // Display 'undefined' 
    alert(this.data('custom').property1) // I get 'TypeError: this.data is not a function' 
    } 
}); 

为什么在source选项我得到undefined而在createselect事件,我得到Hello?我应该如何正确访问search选项上下文中的number属性,以获得Hello

+0

哪里jQuery的包装为 “本”? – kidwon

+0

@kidwon - 对不起,你用“jQuery wrapper”究竟意味着什么? – user12882

+0

我想你最后一次提醒你是在没有jQuery对象的情况下调用jQuery函数,对不对? – kidwon

回答

3

你在这里变得不明确,因为source里面显然this函数是指匿名函数,而不是你在create函数中分配数据的INPUT。

使用其他方法访问source函数中的输入。

$('#input_id').autocomplete({ 
    create: function (event, ui) { 
     // when using "this" here, you're refering to #input_id input 
    }, 
    source: function(request, response) { 
     // when using "this" here, you're refering to anonymous function 
    } 
}); 

要输出功能使用内访问您的数据如下:

// ... 
source: function(request, response) { 
    // you don't need to wrap this.element in jQuery again since it is already wrapped 
    this.element.data('custom').property1 
} 

演示以供将来快速参考:http://jsbin.com/ojesig/1/edit

+0

如何在'source'“block”内引用'#input_id'? – user12882

+0

@ user12882使用:$(this.element).data('custom')。property1 –

+0

@roasted Thx提示 - 尽管快速提示 - this.element已经包装在jQuery中,所以不需要做再次阅读其数据。 – WTK

相关问题