在html代码中添加字符串变量 [英] Adding a string variable inside an html code

查看:123
本文介绍了在html代码中添加字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have an html block that contains few buttons and one text input. The placeholder of this text input should be changed in the different situations. Therefore i add a string variable. Then i put the html inside in another string variable:

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}.

as you can see, in the last line of html code, i added ${dataType} in the placeholder part.

然后我将其与以下代码一起使用:

then i use it with these codes:

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

编译后,在文本输入占位符中显示以下文本:undefined

after compiling, in the text input placeholder, this text appears: undefined

有人可以帮助我该怎么做吗?您的帮助将不胜感激.

Could anyone help me that how i can do it? Your help will be appreciated.

推荐答案

在您的情况下,应在之前定义 dataType 变量,然后在字符串中使用该变量文字(模板):

In your case, your dataType variable should be defined before you will use that variable in your string literal (template):

var dataType = 'HELLO';
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}">`;

console.log(htmlBlock);


已更新:

在这种情况下,您可以这样做:

in this case you could do:

var getHtmlBlock = function(dataType) {
    return `<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}">`;
};

var myDataType =  getHtmlBlock('Add your number');
console.log(myDataType); // replaced string with argument value;

将字符串放入函数中,并通过作为参数传递来替换 $ {dataType} .

Put your string into function, and replace ${dataType} by passing as argument.

这篇关于在html代码中添加字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆