2012-12-06 23 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

相關問題