问题是键和值变量都被设置为对象。如何将它们转换为文本字符串?
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;
});
最佳答案
如果我正确理解您的问题,以下就是您要查找的内容。
jQuery .contents()结果是一个 jQuery 对象。因此,您应该仅从中过滤
文本节点,然后获取其文本
。 (注意:我已使用 .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);
控制台输出:
[pat (1" sq, 1/3" high): "5g", tbsp: "14.2g", cup: "227g", stick: "113g"]
注意: 正如其他人在评论中指出的那样,我也不建议在选择器中使用内联 CSS。您可以将它们放入 CSS 类中,然后在选择器中使用该类,例如 this .
关于javascript - jQuery:从对象数据创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18863834/