我三岁

文章 评论 浏览 28

我三岁 2025-02-21 00:58:09

您可以使用与您要匹配的角色匹配的简单正则正等式,而在数组项目上迭代时。

const arrayToSearch = ["earth (c-137)", "abadango", "citadel of ricks", "worldender's lair", "anatomy park", "interdimensional cable", "immortality field resort", "post-apocalyptic earth", "purge planet", "venzenulon 7", "bepis 9", "cronenberg earth", "nuptia 4", "giant's town", "bird world", "st. gloopy noops hospital", "earth (5-126)", "mr. goldenfold's dream", "gromflom prime", "earth (replacement dimension)", "testicle monster dimension", "signus 5 expanse", "earth (c-500a)", "rick's battery microverse", "the menagerie", "earth (k-83)", "hideout planet", "unity's planet", "dorian 5", "earth (unknown dimension)", "earth (j19ζ7)", "roy: a life well lived", "eric stoltz mask earth", "earth (evil rick's target dimension)", "planet squanch", "glaagablaaga", "resort planet", "interdimensional customs", "galactic federation prison", "gazorpazorp"];

const REGEX_MATCH = /l/ig;

function getCount(array, regex) {
  const matchCount = array.reduce((memo, item) => {
    const matches = item.match(REGEX_MATCH);

    if (matches && matches.length > 0) {
      memo += matches.length;
    }

    return memo;
  }, 0);

  return matchCount;
}

const count = getCount(arrayToSearch, REGEX_MATCH);

console.log(`count is ${count}`);

You can use a simple regex that matches the character that you want to match with while iterating over the array items.

const arrayToSearch = ["earth (c-137)", "abadango", "citadel of ricks", "worldender's lair", "anatomy park", "interdimensional cable", "immortality field resort", "post-apocalyptic earth", "purge planet", "venzenulon 7", "bepis 9", "cronenberg earth", "nuptia 4", "giant's town", "bird world", "st. gloopy noops hospital", "earth (5-126)", "mr. goldenfold's dream", "gromflom prime", "earth (replacement dimension)", "testicle monster dimension", "signus 5 expanse", "earth (c-500a)", "rick's battery microverse", "the menagerie", "earth (k-83)", "hideout planet", "unity's planet", "dorian 5", "earth (unknown dimension)", "earth (j19ζ7)", "roy: a life well lived", "eric stoltz mask earth", "earth (evil rick's target dimension)", "planet squanch", "glaagablaaga", "resort planet", "interdimensional customs", "galactic federation prison", "gazorpazorp"];

const REGEX_MATCH = /l/ig;

function getCount(array, regex) {
  const matchCount = array.reduce((memo, item) => {
    const matches = item.match(REGEX_MATCH);

    if (matches && matches.length > 0) {
      memo += matches.length;
    }

    return memo;
  }, 0);

  return matchCount;
}

const count = getCount(arrayToSearch, REGEX_MATCH);

console.log(`count is ${count}`);

查找一个名称数组中包含了多少次字符

我三岁 2025-02-20 23:52:37

您可以使用 os.environ 对于该任务如下

import os
print("MY_PATH" in os.environ['PATH'])

You might use os.environ for that task as follows

import os
print("MY_PATH" in os.environ['PATH'])

干净的方法来获取python中的Windows路径

我三岁 2025-02-20 22:30:42

不可能基于入口事件属性分支画布。

正如您所说,您能做的最好的方法是使用液体来区分消息步骤中使用的事件或属性。

It isn't possible to branch a Canvas based on entry event properties.

As you said, the best you can do is to use liquid to distinguish which event or property was used in the message step.

使用自定义事件属性进行铜牌中的帆布决策分裂?

我三岁 2025-02-20 20:58:07

newtonsoft.json有一个名为“ JSONCONVERT”的类,

如果您调用

JsonConvert.SerializeObject(data,  new JsonSerializerSettings()
{
   NullValueHandling = NullValueHandling.Ignore
}

,则不会如图所示的序列化null

DefaultValueHandling = DefaultValueHandling.Ignore 

如果您将字符串初始化为空字符串,则使用JSonSerializerSettings可以序列化和避难所


更新

,然后在Deperialize上,它将忽略JSON文件中的null值,而将字符串作为空字符串


答案2:

您还可以写一个自定义jsonConverter继承的字符串转换器

JsonConvert.SerializeObject(data,  new JsonSerializerSettings()
{
   Converters = new List<JsonConverter> { new PartyIdentification() }
}

public class PartyIdentificationConverter: JsonConverter
{
   public override bool CanConvert(Type objectType)
   {
     return typeof(PartyIdentificationConverter).IsAssignableFrom(objectType);
   }

   public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
   {
      reader.Read();
      var p = (PartyIdentificationConverter)reader.Value;

      return p!= null ? p: new PartyIdentificationConverter(); 
   }

   public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
   {
      writer.WriteValue(value);
   }
}

Newtonsoft.Json has a class called "JsonConvert"

If you call

JsonConvert.SerializeObject(data,  new JsonSerializerSettings()
{
   NullValueHandling = NullValueHandling.Ignore
}

Then it will not serialize out null values as shown

You can also set the option

DefaultValueHandling = DefaultValueHandling.Ignore 

to not serialize defaults as well.

Using JsonSerializerSettings both works for serialization and deserialization


Update

If you initialize your strings to empty string -- then on deserialize, it will ignore the null values in the json file, and leave the strings as empty string


Answer 2:

You could also write a custom String converter inheriting off of JsonConverter

JsonConvert.SerializeObject(data,  new JsonSerializerSettings()
{
   Converters = new List<JsonConverter> { new PartyIdentification() }
}

public class PartyIdentificationConverter: JsonConverter
{
   public override bool CanConvert(Type objectType)
   {
     return typeof(PartyIdentificationConverter).IsAssignableFrom(objectType);
   }

   public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
   {
      reader.Read();
      var p = (PartyIdentificationConverter)reader.Value;

      return p!= null ? p: new PartyIdentificationConverter(); 
   }

   public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
   {
      writer.WriteValue(value);
   }
}

Newtonsoft queperialize应该为空而不是null

我三岁 2025-02-19 17:56:47

我有 0 = nonprod ,因为我没有先实例化数组:

declare -A array

I had 0=nonprod because I didn't instantiate the array first :

declare -A array

使用Jenkins Pipeline的bash创建.tfvars文件

我三岁 2025-02-19 14:40:07

我不确定如果没有N对于测试变量,我就会理解您要实现的目标。但是我包括了一个示例。

您可以使用 remove_row_type()函数来删除所选变量的缺失行。

library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.6.1'

trial %>%
  select(age,
         death,
         test1 = response, 
         test2 = response) %>%
  tbl_summary(
    statistic = 
      list(death ~ "{n} ({p}%)",
           c(test1, test2) ~ "") # show no statistics for the test variables
    
  ) %>%
  # remove the missing row for the test variables
  remove_row_type(variables = c(test1, test2), type = "missing") %>%
  as_kable() # convert to kable to display on SO
特征 n = 200
年龄 47(38,57)
未知 11
患者死于 112(56%)
肿瘤反应
肿瘤反应

I am not sure I understand what you're trying to get achieve without the N for the test variables. But i've included an example with what you may be after.

You can use the remove_row_type() function to remove the missing rows for selected variables.

library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.6.1'

trial %>%
  select(age,
         death,
         test1 = response, 
         test2 = response) %>%
  tbl_summary(
    statistic = 
      list(death ~ "{n} ({p}%)",
           c(test1, test2) ~ "") # show no statistics for the test variables
    
  ) %>%
  # remove the missing row for the test variables
  remove_row_type(variables = c(test1, test2), type = "missing") %>%
  as_kable() # convert to kable to display on SO
Characteristic N = 200
Age 47 (38, 57)
Unknown 11
Patient Died 112 (56%)
Tumor Response
Tumor Response

Created on 2022-07-01 by the reprex package (v2.0.1)

GT摘要 - 如何仅在桌子的某些行上删除N&#x27;

我三岁 2025-02-19 05:30:11

多亏了大卫的建议,我成功地解决了自己的问题。

实际上,我的配置中有两个问题。

首先,秘密确实被误解了,然后我将命令/args更改为:

command:
          - "/bin/sh"
          - "-c"
        args:
          - |
            DB_USER=$(cat /secrets/db-user)
            DB_PWD=$(cat /secrets/db-pwd)
            JWT=$(cat /secrets/jwt-secret)
            BUCKET=$(cat /secrets/s3-bucket)
            java -jar  \
            -DSPRING_DATASOURCE_URL=jdbc:mysql://social-mysql.default.svc.cluster.local/api-db?useSSL=false \
            "-DSPRING_DATASOURCE_USERNAME=$DB_USER" \
            "-DSPRING_DATASOURCE_PASSWORD=$DB_PWD" \
            "-DJWT_SECRET=$JWT" \
            "-DS3_BUCKET=$BUCKET" \
            -Dlogging.level.root=DEBUG \
            social-network-api-1.0-SNAPSHOT.jar

设置的内存资源也太低,所以我将它们更改为:

resources:
 limits:
  cpu: 100m
  memory: 400Mi
 requests:
  cpu: 100m
  memory: 400Mi

Thanks to David's suggestion I succeeded in solving my problem.

Actually there were two issues in my configs.

First the secrets were indeed misinterpreted, then I've changed my command/args to:

command:
          - "/bin/sh"
          - "-c"
        args:
          - |
            DB_USER=$(cat /secrets/db-user)
            DB_PWD=$(cat /secrets/db-pwd)
            JWT=$(cat /secrets/jwt-secret)
            BUCKET=$(cat /secrets/s3-bucket)
            java -jar  \
            -DSPRING_DATASOURCE_URL=jdbc:mysql://social-mysql.default.svc.cluster.local/api-db?useSSL=false \
            "-DSPRING_DATASOURCE_USERNAME=$DB_USER" \
            "-DSPRING_DATASOURCE_PASSWORD=$DB_PWD" \
            "-DJWT_SECRET=$JWT" \
            "-DS3_BUCKET=$BUCKET" \
            -Dlogging.level.root=DEBUG \
            social-network-api-1.0-SNAPSHOT.jar

And the memory resources set were also too low, so I have changed them to:

resources:
 limits:
  cpu: 100m
  memory: 400Mi
 requests:
  cpu: 100m
  memory: 400Mi

Kubernetes的春季试图在POD IP上达到DB

我三岁 2025-02-19 05:23:04

从构建类型中确定

任何想基于构建类型设置环境名称的人的构建类型,有方便的 .iaseEnvironment(emoventionName) on webhostbuilder (在Program Main中找到)。

只要针对项目中的构建配置设置了适当的编译符号,就可以执行类似的操作来确定环境名称:

public static void Main(string[] args)
{
    string environmentName;
#if DEBUG
    environmentName = "Development";
#elif STAGING
    environmentName = "Staging";
#elif RELEASE
    environmentName = "Production";
#endif

    var host = new WebHostBuilder()
        .UseKestrel()
        .UseEnvironment(environmentName)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .Build();

    host.Run();
}

Determine EnvironmentName from Build Type

For anybody that would like to set the EnvironmentName based on the build type, there is the handy .UseEnvironment(environmentName) on WebHostBuilder (found in Program Main).

As long as the appropriate compilation symbols are set against the build configurations in your project, you can do something like this to determine the EnvironmentName:

public static void Main(string[] args)
{
    string environmentName;
#if DEBUG
    environmentName = "Development";
#elif STAGING
    environmentName = "Staging";
#elif RELEASE
    environmentName = "Production";
#endif

    var host = new WebHostBuilder()
        .UseKestrel()
        .UseEnvironment(environmentName)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .Build();

    host.Run();
}

如何在.NET Core MVC项目中转换AppSettings.json?

我三岁 2025-02-18 23:29:21

您可以在JSON格式中使用以下规则。

​/I.sstatic.net/yoo7l.png“ alt =”在此处输入映像说明“>

结果:

”

更新:

You could use below rules in the JSON formatting.

enter image description here

enter image description here

enter image description here

Result:

enter image description here

Update:

enter image description here

JSON额外ROWCLASS中的多个if statement

我三岁 2025-02-18 21:58:54

您所描述的内容 - 假设您的启发式是大小/总线程 - 是圆形旋转计划( ie,静态调度),使用chunk_size = 1

#pragma omp parallel for schedule(static,1)

。 ,如果运行时已知(或不知道)迭代的数量,则没有什么区别。

What you are describing -- assuming that your heuristic is size/total threads -- is a round-robin scheduling (i.e., static scheduling) with chunk_size = 1. For that you simply need :

#pragma omp parallel for schedule(static,1)

In this case, it makes no difference if the number of iterations is known (or not) at runtime.

OpenMP:一次分配线程

我三岁 2025-02-18 20:10:28

借助您提供的数据框,这是使用pandas

df["avg"] = (
    pd.concat([pd.Series([6]), df["count"]])[:-1]
    .rolling(2)
    .mean()
    .reset_index(drop=True)
)
print(df)
# Output
         date               days_before  count  avg
0  2020/01/01  [2019/12/31, 2019/12/30]      6  NaN
1  2020/01/02  [2020/01/01, 2019/12/31]      3  6.0
2  2020/01/03  [2020/01/02, 2020/01/01]      2  4.5
3  2020/01/04  [2020/01/03, 2020/01/02]      5  2.5
4  2020/01/05  [2020/01/04, 2020/01/03]      7  3.5

With the dataframe you provided, here is one way to it using pandas rolling:

df["avg"] = (
    pd.concat([pd.Series([6]), df["count"]])[:-1]
    .rolling(2)
    .mean()
    .reset_index(drop=True)
)
print(df)
# Output
         date               days_before  count  avg
0  2020/01/01  [2019/12/31, 2019/12/30]      6  NaN
1  2020/01/02  [2020/01/01, 2019/12/31]      3  6.0
2  2020/01/03  [2020/01/02, 2020/01/01]      2  4.5
3  2020/01/04  [2020/01/03, 2020/01/02]      5  2.5
4  2020/01/05  [2020/01/04, 2020/01/03]      7  3.5

每行都发现的熊猫矢量化平均列

我三岁 2025-02-18 11:16:13

其他两个选项:

基本软件包:

df <- unstack(dat1, form = value ~ numbers)
rownames(df) <- unique(dat1$name)
df

sqldf 软件包:

library(sqldf)
sqldf('SELECT name,
      MAX(CASE WHEN numbers = 1 THEN value ELSE NULL END) x1, 
      MAX(CASE WHEN numbers = 2 THEN value ELSE NULL END) x2,
      MAX(CASE WHEN numbers = 3 THEN value ELSE NULL END) x3,
      MAX(CASE WHEN numbers = 4 THEN value ELSE NULL END) x4
      FROM dat1
      GROUP BY name')

Other two options:

Base package:

df <- unstack(dat1, form = value ~ numbers)
rownames(df) <- unique(dat1$name)
df

sqldf package:

library(sqldf)
sqldf('SELECT name,
      MAX(CASE WHEN numbers = 1 THEN value ELSE NULL END) x1, 
      MAX(CASE WHEN numbers = 2 THEN value ELSE NULL END) x2,
      MAX(CASE WHEN numbers = 3 THEN value ELSE NULL END) x3,
      MAX(CASE WHEN numbers = 4 THEN value ELSE NULL END) x4
      FROM dat1
      GROUP BY name')

如何将数据重新设计为长格式

我三岁 2025-02-18 04:39:27

您遇到的错误是一个相同的问题-princip.html“ rel =” nofollow noreferrer“> Microsoft Q&amp; a 一年前。

您需要将用户添加到SQL DB中,因为AAD用户首先要引起SQLServer。

错误“ Microsoft SQL Server,错误:18456&lt; token-sidendified-principal&gt; ”表示用户用户用于登录到
SQL Server Management Studio无效。通常与
AAD用户未在您尝试连接的SQL DB上添加
(用户数据库或主DB)或AAD用户不是AAD服务器
管理员

您只需要在Azure SQL DB中添加AAD用户即可。您可以关注
这里提到的步骤:
https://learn.microsoft.com/en-us/azure/azure-sql/database/authentication-authentication-authentication-aad-configure?tabs= azure-powershell#创建包含的数据库 - 用户在您的数据库中映射到azure-ad-ad-discities

注意:使用user upn( [email&nbsp; preated] \ name.surname “在我的环境上。

The error you are getting is an identical issue its already been raised over Microsoft Q&A Plateform a year ago.

You need to add the users to your SQL DB as AAD Users first to accces the Specifiv SQLServer.

The error "Microsoft SQL Server, Error: 18456 <token-identified-principal>" means that the user used to login to
SQL Server Management Studio is invalid. It is usually related to an
AAD user which is not added on SQL DB that you are trying to connect
(User DB or Master DB) or that the AAD user is not the AAD Server
Admin.

You just need to add an AAD user in Azure SQL DB. You can follow the
steps mentioned here:
https://learn.microsoft.com/en-us/azure/azure-sql/database/authentication-aad-configure?tabs=azure-powershell#create-contained-database-users-in-your-database-mapped-to-azure-ad-identities

Note : Use User UPN([email protected]) to access the SQL DB not logged on as this user: "domain\name.surname" on my environment.

用户失败的登录失败&#x27;&lt; token识别的principal&gt;&#x27;。 (Microsoft SQL Server,错误:18456)

我三岁 2025-02-18 04:22:19

似乎executorService.awaitxxx和shutdown()不会阻止
主线程

方法等待()确实 block 调用线程,但是您已经指定了 0 秒的超时。引用 javadoc

块,直到关闭请求或超时发生后所有任务都完成执行,或者当前线程被中断,以先到者为准。

如果您期望等待()将中断提交的任务,那么您的期望是错误的,那就不会了。此方法仅允许您指定等待期间并报告执行者是否完成的时间。

返回:
如果该执行人终止,则为false,如果终止之前的超时

超时

方法 shutdown() 也将 not> not 中断先前提交的任何任务:

启动有序的关机,在该关闭中,在该关闭中执行了先前提交的任务,但不会接受新任务。

如果您想尝试中断提交的任务,请使用 shutdownnow()

试图停止所有积极执行任务,停止处理任务的处理,并返回等待执行的任务列表。

注意:使用 shutdown()是一种首选方法。

Seems the ExecutorService.awaitXXX and shutdown() doesn't block the
main thread

Method awaitTermination() does block the calling thread, but you've specified the timeout of 0 seconds. Quote from the javadoc:

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

In case if you expected that awaitTermination() will interrupt submitted tasks, then your expectation is wrong, it wouldn't do that. This method only allows you to specify the period to wait and reports whether executor is done or not.

Returns:
true if this executor terminated and false if the timeout elapsed before termination

Method shutdown() also will not interrupt any tasks that are previously submitted:

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

If you wish to try to interrupt submitted tasks, use shutdownNow().

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

Note: usage of shutdown() is a preferred approach.

Java executorService.awaitTermination()是否会阻止主线程并等待?

我三岁 2025-02-18 00:31:04

document.queryselectorall('。unit-lenght')在DOM更改时不会更新。而不是调用 querySelectorall()创建数组时,请将选择器放入 db_localization array array和call queryselectorall(QuerySelectorall() ()

var language = document.documentElement.lang.toLowerCase();

/* ----- locailization_database.js ----- */
var DB_localization = [
  /* content */
  [
    [
      'DB_localization/content/text-block-2a',
      document.querySelector('#text-block-2'),
      'text',
      {
        de: `In Deutschland gibt es noch keine Gesetze, die artgerechte Haltung 
                     vorschreiben. Dennoch gibt es Richtlinien, nach welchen auch einige 
                     Veterinärämter handeln.`,
        us: 'not localized',
        en: 'not localized'
      }
    ],
    [
      'DB_localization/content/text-block-2b',
      document.querySelector('#text-block-2'),
      'tag',
      {
        de: '',
        us: '',
        en: ''
      },
      'br',
      ''
    ],
    [
      'DB_localization/content/text-block-2c',
      document.querySelector('#text-block-2'),
      'text',
      {
        de: `Die Tierärztliche Vereinigung für Tierschutz e.V. (TVT), das 
                     Bundesministerium für Ernährung und Landwirtschaft (BMEL) sowie der 
                     Sachkundenachweis für Kleinsäuger nach §11 Tierschutzgesetz, empfehlen ein 
                     Gehegemaß für alle Hamsterarten ab `
          /*<span class="minimum-surface-area"></span>
                               <span class="unit-lenght"></span>. */
          ,
        us: 'not localized',
        en: 'not localized'
      }
    ],
    [
      'DB_localization/content/text-block-2d',
      document.querySelector('#text-block-2'),
      'tag',
      {
        de: '',
        us: '',
        en: ''
      },
      'span',
      'minimum-surface-area'
    ],
    [
      'DB_localization/content/text-block-2e',
      document.querySelector('#text-block-2'),
      'tag',
      {
        de: '',
        us: '',
        en: ''
      },
      'span',
      'unit-lenght'
    ]
  ],

  /* measurement units */
  [
    [
      'DB_localization/units/lenght',
      '.unit-lenght',
      {
        de: 'cm',
        us: 'in',
        en: 'cm'
      }
    ],
    [
      'DB_localization/units/surface-area-A',
      '.unit-surface-area-A',
      {
        de: 'm²',
        us: 'not localized',
        en: 'm²'
      }
    ],
    [
      'DB_localization/units/surface-area-B',
      '.unit-surface-area-B',
      {
        de: 'cm²',
        us: 'ft²',
        en: 'cm²'
      }
    ],
    [
      'DB_localization/units/factor',
      '.unit-factor',
      {
        de: 'x',
        us: 'x',
        en: 'x'
      }
    ],
    [
      'DB_localization/units/minimum-surface-area',
      '.minimum-surface-area',
      {
        de: '100x50',
        us: '32x18',
        en: '100x50'
      }
    ],
  ]
];

/* ----- localization.js ----- */
window.addEventListener('load', function() {
  /* loading unique elements */
  for (let i = 0; i < DB_localization[0].length; i++) {
    let DB_array_element = DB_localization[0][i][1],
      DB_array_type = DB_localization[0][i][2],
      DB_array_value = DB_localization[0][i][3][language];
    if (typeof DB_array_element !== 'undefined' &&
      typeof DB_array_type !== 'undefined' &&
      typeof DB_array_value !== 'undefined') {
      if (DB_array_type == 'text') {
        DB_array_element.insertAdjacentHTML('beforeend', DB_array_value);
      }
      if (DB_array_type == 'tag') {
        let DB_array_tag = DB_localization[0][i][4],
          DB_array_class = DB_localization[0][i][5];
        let new_ele = document.createElement(DB_array_tag);
        DB_array_element.appendChild(new_ele);
        if (DB_array_class !== '') {
          new_ele.setAttribute('class', DB_array_class);
        }
      }
      array_path = DB_localization[0][i][0];
    } else {
    }

    if (i + 1 === DB_localization[0].length) {
      apply_units();
    }
  }

});

function apply_units() {
  /* applying the correct measurement units */
  for (let i = 0; i < DB_localization[1].length; i++) {
    let DB_array_element = document.querySelectorAll(DB_localization[1][i][1]),
      DB_array_value = DB_localization[1][i][2][language];
    if (typeof DB_array_value !== 'undefined' &&
      typeof DB_array_element !== 'undefined') {
      DB_array_element.forEach(el => el.insertAdjacentHTML('beforeend', DB_array_value));
      array_path = DB_localization[1][i][0];
    } else {
    }
  }
}
<!DOCTYPE html>
<html lang="de" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Einstreu-Rechner</title>
</head>

<body>

  <main class="py-l px-xl mx-auto mt-xl">

    <!-- ----- Section: Title ----- -->
    <h1 id="title"></h1>

    <!-- ----- Section: Description ----- -->
    <section id="description" title="Beschreibung über die Richtlininen des deutschen Standards">
      <p class="text-align-justify" id="text-block-1"></p>
      <p class="text-align-justify" id="text-block-2"></p>
      <h3 class="text-align-center" id="sub-title-1"></h3>
      <p class="text-align-center text-color-red" id="text-block-3"></p>
      <h4 class="text-align-center" id="sub-title-2"></h4>
    </section>

    <!-- More Content -->
    
    <p>This span works:</p>
    <span class="unit-lenght"><span>

document.querySelectorAll('.unit-lenght') doesn't update when the DOM changes. Instead of calling querySelectorAll() when creating the array, put the selector in the DB_localization array and call querySelectorAll() when calling forEach().

var language = document.documentElement.lang.toLowerCase();

/* ----- locailization_database.js ----- */
var DB_localization = [
  /* content */
  [
    [
      'DB_localization/content/text-block-2a',
      document.querySelector('#text-block-2'),
      'text',
      {
        de: `In Deutschland gibt es noch keine Gesetze, die artgerechte Haltung 
                     vorschreiben. Dennoch gibt es Richtlinien, nach welchen auch einige 
                     Veterinärämter handeln.`,
        us: 'not localized',
        en: 'not localized'
      }
    ],
    [
      'DB_localization/content/text-block-2b',
      document.querySelector('#text-block-2'),
      'tag',
      {
        de: '',
        us: '',
        en: ''
      },
      'br',
      ''
    ],
    [
      'DB_localization/content/text-block-2c',
      document.querySelector('#text-block-2'),
      'text',
      {
        de: `Die Tierärztliche Vereinigung für Tierschutz e.V. (TVT), das 
                     Bundesministerium für Ernährung und Landwirtschaft (BMEL) sowie der 
                     Sachkundenachweis für Kleinsäuger nach §11 Tierschutzgesetz, empfehlen ein 
                     Gehegemaß für alle Hamsterarten ab `
          /*<span class="minimum-surface-area"></span>
                               <span class="unit-lenght"></span>. */
          ,
        us: 'not localized',
        en: 'not localized'
      }
    ],
    [
      'DB_localization/content/text-block-2d',
      document.querySelector('#text-block-2'),
      'tag',
      {
        de: '',
        us: '',
        en: ''
      },
      'span',
      'minimum-surface-area'
    ],
    [
      'DB_localization/content/text-block-2e',
      document.querySelector('#text-block-2'),
      'tag',
      {
        de: '',
        us: '',
        en: ''
      },
      'span',
      'unit-lenght'
    ]
  ],

  /* measurement units */
  [
    [
      'DB_localization/units/lenght',
      '.unit-lenght',
      {
        de: 'cm',
        us: 'in',
        en: 'cm'
      }
    ],
    [
      'DB_localization/units/surface-area-A',
      '.unit-surface-area-A',
      {
        de: 'm²',
        us: 'not localized',
        en: 'm²'
      }
    ],
    [
      'DB_localization/units/surface-area-B',
      '.unit-surface-area-B',
      {
        de: 'cm²',
        us: 'ft²',
        en: 'cm²'
      }
    ],
    [
      'DB_localization/units/factor',
      '.unit-factor',
      {
        de: 'x',
        us: 'x',
        en: 'x'
      }
    ],
    [
      'DB_localization/units/minimum-surface-area',
      '.minimum-surface-area',
      {
        de: '100x50',
        us: '32x18',
        en: '100x50'
      }
    ],
  ]
];

/* ----- localization.js ----- */
window.addEventListener('load', function() {
  /* loading unique elements */
  for (let i = 0; i < DB_localization[0].length; i++) {
    let DB_array_element = DB_localization[0][i][1],
      DB_array_type = DB_localization[0][i][2],
      DB_array_value = DB_localization[0][i][3][language];
    if (typeof DB_array_element !== 'undefined' &&
      typeof DB_array_type !== 'undefined' &&
      typeof DB_array_value !== 'undefined') {
      if (DB_array_type == 'text') {
        DB_array_element.insertAdjacentHTML('beforeend', DB_array_value);
      }
      if (DB_array_type == 'tag') {
        let DB_array_tag = DB_localization[0][i][4],
          DB_array_class = DB_localization[0][i][5];
        let new_ele = document.createElement(DB_array_tag);
        DB_array_element.appendChild(new_ele);
        if (DB_array_class !== '') {
          new_ele.setAttribute('class', DB_array_class);
        }
      }
      array_path = DB_localization[0][i][0];
    } else {
    }

    if (i + 1 === DB_localization[0].length) {
      apply_units();
    }
  }

});

function apply_units() {
  /* applying the correct measurement units */
  for (let i = 0; i < DB_localization[1].length; i++) {
    let DB_array_element = document.querySelectorAll(DB_localization[1][i][1]),
      DB_array_value = DB_localization[1][i][2][language];
    if (typeof DB_array_value !== 'undefined' &&
      typeof DB_array_element !== 'undefined') {
      DB_array_element.forEach(el => el.insertAdjacentHTML('beforeend', DB_array_value));
      array_path = DB_localization[1][i][0];
    } else {
    }
  }
}
<!DOCTYPE html>
<html lang="de" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Einstreu-Rechner</title>
</head>

<body>

  <main class="py-l px-xl mx-auto mt-xl">

    <!-- ----- Section: Title ----- -->
    <h1 id="title"></h1>

    <!-- ----- Section: Description ----- -->
    <section id="description" title="Beschreibung über die Richtlininen des deutschen Standards">
      <p class="text-align-justify" id="text-block-1"></p>
      <p class="text-align-justify" id="text-block-2"></p>
      <h3 class="text-align-center" id="sub-title-1"></h3>
      <p class="text-align-center text-color-red" id="text-block-3"></p>
      <h4 class="text-align-center" id="sub-title-2"></h4>
    </section>

    <!-- More Content -->
    
    <p>This span works:</p>
    <span class="unit-lenght"><span>

foreach不适用于动态生成的元素

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文