首页 > 解决方案 > 在 html 代码中添加字符串变量

问题描述

我有一个包含几个按钮和一个文本输入的 html 块。此文本输入的占位符应在不同情况下更改。因此我添加了一个字符串变量。然后我将 html 放入另一个字符串变量中:

var dataType;

var htmlBlock = `<div class="icon negative big toleft" id="cancel-btn"><i class="fas fa-minus-circle"></i></div>
<div class="icon add big toleft"><i class="fas fa-check-circle"></i></div>
<input type="text" class="contact-input" style="margin-bottom: 5px;" maxlength="50" name="my-contact-phone" data-name="Name" placeholder=${dataType}>`

如您所见,在最后一行 html 代码中,我在占位符部分添加了 ${dataType}。

然后我将它与这些代码一起使用:

if (document.getElementsByClassName('.js-phone'))
{
  dataType = "Add your number "
  this.html = this.phone.html();
  this.phone.html(
    htmlBlock
  )
};

编译后,在文本输入占位符中,出现这个文本:undefined

谁能帮助我,我该怎么做?您的帮助将不胜感激。

标签: javascripthtml

解决方案


您的占位符需要用双引号“”括起来。如果您需要 $(dataType) 将值作为占位符放入(我假设为 jQuery 值),您需要像这样连接字符串:

placeholder="' + dataType + '"

不要错过连接的双引号之间的单引号。看起来您正在尝试使用 jquery 获取和设置值。最好获取一个对象的值,例如 $(myVal).val(),然后使用该变量将其设置到您的其他代码中。


推荐阅读