[英]jQuery: Creating an array from object data
問題在於鍵和值變量都被設置為對象。 如何將它們轉換為文本字符串?
units = [];
$('thead th[style*="width:130px;line-height:1.2em;text-align:center"]').each(function() {
key = $(this).contents('')[4];
value = $(this).contents('')[6];
units[key] = value;
});
關鍵值到底是什么? 您可以改用JSON方法嗎? 使用JSON.stringify() method
轉換JSON對象將更加干凈和容易。
var foo = {};
foo.bar = "new property";
foo.baz = 3;
var JSONfoo = JSON.stringify(foo);
有關更多信息,請參見此處 。
如果我正確理解了您的問題,那么以下是您要尋找的內容。
jQuery .contents()生成一個jQuery對象。 因此,您應該僅從中filter
文本節點,然后獲取其text
。 (注意:我已經使用.trim()
清除了多余的空格/換行符)。
jQuery的:
units = [];
$('thead th[style*="width:130px;line-height:1.2em;text-align:center"]').each(function () {
key = $(this).contents().filter(function () {
return this.nodeType === 3;
}).eq(2).text().trim();
value = $(this).contents().filter(function () {
return this.nodeType === 3;
}).eq(3).text().trim();
units[key] = value;
});
//console.log(units);
控制台輸出:
[拍打(1平方英尺,高1/3英寸):“ 5g”,湯匙:“ 14.2g”,杯子:“ 227g”,棒子:“ 113g”]
注意:正如其他人已經在注釋中指出的那樣,我也不建議在選擇器中使用內聯CSS。 您可以將它們放入CSS類中,然后像這樣在選擇器中使用該類。
我認為這可能會有所幫助。
var units = [];
$('thead th[style*="width:130px;line-height:1.2em;text-align:center"]').each(function() {
key = $(this).text();
console.log(key);
value = $(this).contents('input[type=text]').val();
console.log(value);
units[key] = value;
});
for(var i in units){
console.log(units[i]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.