1

问题是键和值变量都被设置为对象。如何将这些转换为文本字符串?

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;

});

JSBin 问题

4

3 回答 3

0

究竟什么是键值?您可以使用 JSON 方式吗?使用JSON.stringify() method.

var foo = {};
foo.bar = "new property";
foo.baz = 3;

var JSONfoo = JSON.stringify(foo);

请参阅此处了解更多信息。

于 2013-09-18T04:51:56.407 回答
0

如果我正确理解了您的问题,那么您正在寻找以下内容。

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 英寸高):“5 克”,汤匙:“14.2 克”,杯子:“227 克”,棍子:“113 克”]

工作演示

注意:正如其他人已经在评论中指出的那样,我也不建议在选择器中使用内联 CSS。您可以将它们放入 CSS 类中,然后像这样在选择器中使用该类

于 2013-09-18T05:30:24.733 回答
0

我认为这可能会有所帮助。

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]);
}
于 2013-09-18T06:28:11.830 回答