【问题标题】:Replacing Multiple Strings with Images in Javascript用 Javascript 中的图像替换多个字符串
【发布时间】: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


【解决方案1】:

我将从描述搜索和替换字符串的对象数组开始,然后循环遍历它以进行搜索和替换。这是一个最小的例子。

let searchAndReplace = [
  { search: "{A}", replace: "path-to-image-a.png"},
  { search: "{B}", replace: "path-to-image-b.png"}
];

for(let s of searchAndReplace) {
  document.body.innerHTML = document.body.innerHTML.replace(s.search, s.replace);
}

当然,您可以使用 PHP 动态填充该数组。

您可能还想对搜索词使用正则表达式。

var searchAndReplace = [
  { search: /{A}/g, replace: "path-to-image-a.png"},
  { search: /{B}/g, replace: "path-to-image-b.png"}
];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多