【问题标题】:How to insert variables into text when storing content in an object?将内容存储在对象中时如何将变量插入文本?
【发布时间】:2010-11-11 15:04:10
【问题描述】:

我正在使用下面的代码将内容插入页面。我需要在文本中插入一些变量以生成一些动态值,但不确定如何执行此操作。谁能告诉我需要改变什么?

这是我如何在 JS 中存储数据的精简示例:

var fruit = {
    'apples': {
        'goldenDelicious' : {
            color: 'yellow',
            sale: 'A sale of $XXXXX (need to insert a number in here). Be sure to buy some before they are all gone!',
            link: {
                linkText: ('This company sells this for $XXXXX (eed to insert a price here). Click here to visit their site.'),
                url: 'I NEED TO INSERT THE URL HERE'
            }
        }
    }
}

这是我如何称呼它的一个例子:(它比这更动态,但你明白了)

var fruitType = 'apples';
var fruitVariety = 'goldenDelicious';

fruit[fruitType][fruitVariety], function () {
    // do something
});

所以我希望能够在对象中插入价格、销售和 URL 等值。

【问题讨论】:

  • 您应该保持数据原样,并在呈现它们时进行转换(我猜是 HTML 格式)。这正是 javascript 模板引擎所做的。

标签: javascript arrays object


【解决方案1】:

有很多方法可以做到这一点。如果您要进行大量此类替换,您可能需要查看模板引擎。我一直在使用Trimpath,对此我很满意。

如果您还不想花哨,请将您自己的占位符标记放入字符串中,然后替换它们。

var fruit = {
    'apples': {
        'goldenDelicious' : {
            color: 'yellow',
            sale: 'A sale of PLACEHOLDER_1. Be sure to buy some before they are all gone!',
            link: {
                linkText: ('This company sells this for PLACEHOLDER_2. Click here to visit their site.'),
                url: 'I NEED TO INSERT THE URL HERE'
            }
        }
    }
}

fruit.apples.goldenDelicious.sale = fruit.apples.goldenDelicious.sale.replace("PLACEHOLDER_1", "the real value");

【讨论】:

  • 感谢您的帮助!它似乎不想使用点符号 - 它只会使用括号。任何想法为什么?我需要去定义goldenDelicious和sale吗?我尝试将它们放在引号中,但这也无济于事。
猜你喜欢
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 2021-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多