代码之家  ›  专栏  ›  技术社区  ›  Cofey

在对象中存储内容时,如何在文本中插入变量?

  •  0
  • Cofey  · 技术社区  · 14 年前

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

    下面是我在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等值。

    1 回复  |  直到 14 年前
        1
  •  1
  •   morgancodes    14 年前

    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");