2010-11-11 34 views
0

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

这里是我如何保存在我的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插入到对象的价值。

+0

你应该保持你的数据不变,并在渲染时进行转换(我猜想是HTML)。这正是JavaScript模板引擎所要做的。 – Mic 2010-11-11 15:58:06

回答

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

感谢您的帮助!它似乎不想使用点符号 - 它只会使用括号。任何想法为什么?我是否需要去定义goldenDelicious和销售?我试图把它们放在引号中,但这也没有帮助。 – Cofey 2010-11-11 15:46:32

相关问题