2017-08-30 84 views
0

下面,您可以找到我正在使用的「選定」-Object的屏幕截圖。這是一個選擇列表。我收到以下代碼的對象(使用jQuery):通過變量訪問數據屬性值

var addArticle = $('.add-article'); // div.add-article 
// selector is a dynamic value, that defines, which select-list should be "found" 
var select = addArticle.find('[data-id=' + selector + ']'); 

對象選擇正常。但是,當我想獲得數據屬性值(值是數字),我無法得到它們。

Object image here

我試了很多變化,以獲取值,但這裏是它的一個例子

//$this.selectors is an array with all values beween data- and -id 
$.each($this.selectors, function (i, el) { 
    //return if last needed data attribute was read 
    if (i == $this.lastAsInt) { 
     return false; 
    } 
    // "generate" data-selector 
    selector = '[data-' + el + '-id]'; 

    // select = object from the image (see link), also tried with data() 
    location[el] = select.find(':selected').find(selector); 
}); 

我希望有人能理解我的問題:)

+0

它真的不清楚你問什麼,但如果你想從'data'選擇元素屬性您打造'selector',那麼你需要像這樣將它包裝在'[]'中:'selector ='[data-'+ el +'-id]';'。如果這不是你所需要的,那麼請編輯你的問題,以使你想要做的更清楚 –

回答

0

比方說你有一個變量,你存儲你的「選定」對象,例如var myObject

然後,你可以簡單地獲取數據attr與jQuery的.data() ibute:

myObject.data('room-id'); 

這裏是一個Fiddle

+0

在我的情況下,這是行不通的。我必須通過myObject.data(變量)訪問數據屬性。 –

+0

我很抱歉。我的問題是,該對象無法在函數內部讀取(bc accessibility ...) –