[英]Can I use a variable in JS for my html?
I have a JS file CharacterSelection
where a user can select an avatar and type their name into a textarea.我有一个 JS 文件CharacterSelection
,用户可以在其中 select 一个头像并将他们的名字输入到文本区域。
Now I want to set a text div in an html file to the contents of the textarea.现在我想将 html 文件中的文本 div 设置为 textarea 的内容。 I will use it to display the player's name at a specific location on the screen.我将使用它在屏幕上的特定位置显示玩家的名字。
I know that I can set a div to a text, such as: <div id ="statSheetExitButton">Exit</div>
will show "Exit" (style and location depending on css)我知道我可以将 div 设置为文本,例如: <div id ="statSheetExitButton">Exit</div>
将显示“Exit”(样式和位置取决于 css)
I'm wondering if there is any way to put a String variable in there, since I will not know what name the player enters.我想知道是否有任何方法可以在其中放置一个字符串变量,因为我不知道玩家输入的名称。
I grab the textarea's contents using var name = $("#nameTextBox").val();
我使用var name = $("#nameTextBox").val();
获取文本区域的内容
I'm thinking that saying <div id ="playerName">name</div>
will display the text "name".我认为说<div id ="playerName">name</div>
将显示文本“名称”。
Is there a way to accomplish my goal?有没有办法实现我的目标?
$("#nameTextBox").change(function(){
$("#playerName").html($(this).val());
});
This will attach an event handler to the textbox so everytime the name changes the div is updated.这会将事件处理程序附加到文本框,因此每次更改名称时都会更新 div。
Here is a working example.这是一个工作示例。 http://jsfiddle.net/2NkTb/ http://jsfiddle.net/2NkTb/
Please note that for the onchange event you must tab out of textbox or the textbox must lose focus请注意,对于 onchange 事件,您必须在文本框中跳出标签,否则文本框必须失去焦点
var name = $("#nameTextBox").val();
$("#playerName").html(name);
Do this:做这个:
var name = $("#nameTextBox").val();
$('#playerName').text(name);
You could do something like this which will replace the html of the tag with your JavaScript string:您可以执行以下操作,将标签的 html 替换为您的 JavaScript 字符串:
$('#playerName').html(myNameVar);
Other than that, I don't think you can directly inject JavaScript variables like you would in a template language.除此之外,我认为您不能像在模板语言中那样直接注入 JavaScript 变量。
Try:尝试:
$('#playerName').html($("#textbo").val());
var playerName = 'John Dow'
document.getElementById('playerName').innerHTML=playerName
You need to set the property innerHTML of you div element.您需要设置 div 元素的属性 innerHTML。
$("playerName").innerHTML = name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.