javascript - 在 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
谁能帮助我,我该怎么做?您的帮助将不胜感激。
解决方案
您的占位符需要用双引号“”括起来。如果您需要 $(dataType) 将值作为占位符放入(我假设为 jQuery 值),您需要像这样连接字符串:
placeholder="' + dataType + '"
不要错过连接的双引号之间的单引号。看起来您正在尝试使用 jquery 获取和设置值。最好获取一个对象的值,例如 $(myVal).val(),然后使用该变量将其设置到您的其他代码中。
推荐阅读
- python - Kill program generated by subprocess with PyQt5
- c# - 在c#中实现数组数据结构
- javascript - WKWebView - 防止用户文本选择触发的自动滚动
- r - 如何在不重复列名的情况下使用 readr::write_excel_csv 附加数据?
- javascript - jQuery中IMG URL文件夹位置的拇指旋转器
- python - 如何将文件从 django 发送到 python 脚本?
- linux - 无法获取命令输出的绝对值
- javascript - instanceof 为我的自定义异常类返回错误
- python-3.x - 从连接到串行端口的设备丢失数据
- javascript - 点击视频播放器更新图标