【发布时间】:2020-02-29 08:40:39
【问题描述】:
我目前有54 图像图标,在以后的阶段我将拥有多个200 图像图标,这些图标需要replace 各种strings 贯穿整个html 页面。在所有情况下,这些strings 将是encased in {}。
示例
{A},
{B},
{C},
{ABC},
{DEF},
{1},
{2},
{34},
etc.
到目前为止,这就是我想出的所有可行的方法,但仅适用于个人。
<script>
var link = '<img src="path_to_IMG" height="15px" width="15px">';
$("body").children().each(function () {
$(this).html( $(this).html().replace(/{B}/g, link) );
});
</script>
我希望脚本循环遍历所有情况,动态更改 path_to_IMG 并用图像链接替换字符串。请原谅,我是 Javascript 的新手,所以我下面的示例显示的元素好像部分是 PHP。该脚本将随着新图标不断发展,并且随着时间的推移将不断添加这些图标的路径。
<script>
$path = 'website.com/images/';
$img_loc = 'IMG_GENERIC.png';
$link = '<img src=".$path.$img_loc." alt="symbol" height="15px" width="15px" />';
$("body").children().each(function ()
{
case('{A}'):
$img_loc = 'IMG_A.png';
$(this).html( $(this).html().replace(/{A}/g, link) );
case('{B}'):
$img_loc = 'IMG_B.png';
$(this).html( $(this).html().replace(/{B}/g, link) );
});
</script>
【问题讨论】:
-
这和 PHP 有什么关系?您发布的代码中没有 PHP
-
我会将所有这些存储到一个对象中 - 使用您需要替换的字符串作为键,使用您需要替换的字符串作为值。然后只需遍历对象,然后……替换。
标签: javascript php jquery arrays replace