gpt4 book ai didi

javascript - 如何将 Javascript 反向引用传递给键或函数?

转载 作者:行者123 更新时间:2023-11-29 09:59:31 25 4
gpt4 key购买 nike

<script type='text/javascript'>

// I have template and info
var img_template = "<img src='{src}' width='{width}' height='{height}' title='{title}' />";
var img_info = {
src : 'http://myimage.com/img.jpg',
width: '100px',
height: '100px',
title: 'My Image'
}

// I want to put info to template but It's not work.
// How should I do ?
var my_image = img_template.replace(/{(.+?)}/g, img_info['$1']);

</script>

最佳答案

使用函数进行替换:

<script type='text/javascript'>
var img_template = "<img src='{src}' width='{width}' height='{height}' title='{title}' />";
var img_info = {
src : 'http://myimage.com/img.jpg',
width: '100px',
height: '100px',
title: 'My Image'
}

var my_image = img_template.replace(/{(.+?)}/g, function(a,b){
return img_info[b];
});
</script>

关于javascript - 如何将 Javascript 反向引用传递给键或函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4377904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com