2014-08-27 39 views
1

我試圖獲取一個數據字段屬性來選擇我的「objects.json」的字段將用作我的Bootstrap Typeahead輸入文本的源,如:在引導程序中使用html輸入數據字段屬性typehead

form.html

<input type="text" data-provide="typeahead" data-field="name"> 

form.js

$("[data-provide=typeahead]").typeahead({ 
    source: function(query, process) { 
    return $.get("/objects.json", { 
     query: query 
    }, function(data) { 
     return process($.map(data, function(o) { 
     return o[$(this).data('field')]; 
     })); 
    }); 
    } 
}); 

objects.json

[{"id":1,"name":"lorem"}, 
{"id":2,"name":"ipsum"}, 
{"id":3,"name":"dolor"}] 

問題是JavaScript上的「$(this).data('field')」沒有獲得HTML數據字段屬性。

在此先感謝!

回答

0

您是否試過使用$(this).attr('data-field')?我還你可能想看看這裏: http://api.jquery.com/attribute-equals-selector/也可能會出現一些你的問題,這取決於無論您甚至讓你的初始元素

+0

是的,我已經嘗試過: (this).getAttribute('data-field') $(this).prop('data-field') $(this)。$(this).attr('data-field') $(this).getAttribute('data-field') 數據('字段') 沒有任何工作。我得到了json數據,但Typeahead列表未加載。 – leomperes 2014-08-27 20:43:47

0

試試這個:

$("[data-provide=typeahead]").typeahead({ 
    source: function(query, process) { 
    return $.get("/objects.json", { 
    query: query 
    }, function(data) { 
     return process($.map(data, function(o) { 
     return o[$(this).attr('data-field')]; //<-- Use attr() 
     })); 
    }); 
    } 
}); 
+0

是的,我已經試過了: $(this).attr('data-field') $(this).getAttribute('data-field') $(this).prop('data-field ') $(this).data('field')' 沒什麼用。我得到了json數據,但Typeahead列表未加載。 – leomperes 2014-08-27 20:44:10

相關問題