如何将变量设置为输入字段的标签?

时间:2017-07-03 02:28:19

标签: javascript jquery

以下是我的示例输入字段:

<div class="md-form form-sm">
    <input type="text" id="form1" class="form-control">
    <label for="form1" class="">Example label</label>
</div>

如果我想将标签设置为变量,那么我可以更新它。我该怎么办?请记住,我是JS和Jquery的新手,这些是我目前使用的唯一工具。我没有使用任何其他框架,除非绝对必要,否则我不愿意这样做。

4 个答案:

答案 0 :(得分:0)

您正在寻找一些动态模板框架。我使用过Underscore.js,它具有完成工作的模板功能:

http://underscorejs.org/#template

答案 1 :(得分:0)

> from: <label for="form1" class="">Example label</label>
> ˀ
> to: 
<label for="form1" class=""><div id="mylabel">Example
 label</div></label>

<script>
     content = "this is my variable text";
     document.getElementById("mylabel").innerHTML = content; 
</script>

答案 2 :(得分:0)

你可以使用纯JS / jQuery来做到这一点。

首先,创建一个链接到DOM元素的变量(假设你给它一个label类):

var test = $(".label")[0];

然后,您只需更改其innerHTML字段的值即可更改其中的文字:

test.innerHTML = "test";

因此,您的完整代码将如下:

var test;

window.onload = function() {
  test = $(".label")[0];
  
  //At any other point in your code when you would want to change it
  test.innerHTML = "Another label";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="md-form form-sm">
    <input type="text" id="form1" class="form-control">
    <label for="form1" class="label">Example label</label>
</div>

我不相信有更好的方法(即只设置一个变量而不是属性),而不是使用其他框架 - 例如其他人提到的swalled

答案 3 :(得分:0)

我要感谢大家的回答。就像我说的,我是JS的新手,我很感激所有的帮助。我最终这样做了:

我输入的输入:

<div class="md-form form-sm">
    <input type="text" id="blueCartQty" maxlength="2" class="form-
        control">
    <label for="blueCartQty" id="blueInputLabel" class=""></label>
</div>

并将我的变量作为标签放在我的JS文件中:

$("#blueInputLabel").html(cart.blueQty);

cart.blueQty在函数中得到更新,我希望它始终显示当前值。