如何用一些动态值替换跨度内容

时间:2018-10-14 10:11:30

标签: javascript jquery

我有一个字符串,其值为

"My name is <span data-name-attribute></span>  <span class="icon icon>is</span>  <span data-job-attribute></span>. May I help you "

我需要根据开始和结束span标签对它们进行拆分,并且最终输出应该是

Your name is John and my profession is Welder. May I help you.

“约翰”的动态价值来自于经过一番反复的替换,而“我的职业是”被替换为is并被替换为“ Welder”

任何帮助都将非常有帮助,在此先感谢

2 个答案:

答案 0 :(得分:0)

具有这样的html:

serial1

您可以定位跨度并更改其文本,如下所示:

<p class="example">His name is <span data-name>unknown</span>.</p>

关于编码环境的示例:this answer

答案 1 :(得分:0)

这是获得该结果的非常基本的方法。

// store the information in an object for convenience
const obj = {name: 'John', job: 'Welder'};
const str = 'My name is <span data-name-attribute></span>  <span class="icon icon">is</span>  <span data-job-attribute></span>. May i help you?';

// add the string to the document body as HTML
document.body.innerHTML = str;

// grab the relevant span elements
const name = document.body.querySelector('[data-name-attribute]')
const job = document.body.querySelector('[data-job-attribute]');

// insert the name
name.textContent = obj.name;

// add the profession text after the name span
name.insertAdjacentHTML('afterend', ' and my profession');

// add the job text
job.textContent = obj.job;

更好的方法是将字符串保留为template literal,可以在其中插入变量值。

const obj = {name: 'John', job: 'Welder'};

function replacer({name, job}) {
  return `My name is ${name} and my profession is ${job}. May i help you?`;
}

document.body.innerHTML = replacer(obj);