在对象中存储内容时如何将变量插入文本?
我正在使用下面的代码将内容插入到页面中。我需要在文本中插入一些变量以生成一些动态值,但不确定如何执行此操作。有人可以告诉我我需要改变什么吗?
这是我如何在 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 等值插入到对象中。
I'm using the code below to insert content into a page. I need to insert some variables in the text to generate some dynamic values and am unsure how to do this. Can someone tell me what I'd need to change?
Here's a slimmed down example of how I'm storing the data in my 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'
}
}
}
}
Here's an example of how I'm calling it: (it's more dynamic than this, but you get the idea)
var fruitType = 'apples';
var fruitVariety = 'goldenDelicious';
fruit[fruitType][fruitVariety], function () {
// do something
});
So what I'd like is to be able to insert values like a price, sale, and URL into the object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有很多方法可以做到这一点。如果您要进行大量此类替换,您可能需要考虑模板引擎。我一直在使用 Trimpath,并且对此感到满意。
如果您还不想那么花哨,请将您自己的占位符标记放入字符串中,然后替换它们。
There are a bunch of ways to do this. If you're going to be doing a lot of this type of replacement, you'll probably want to look at a templating engine. I've been using Trimpath, and am happy with it.
If you don't want to get that fancy yet, put your own placeholder tokens in the string and then replace them.