简体   繁体   English

尝试将html属性设置为javascript变量

[英]Trying to set an html attribute to a javascript variable

I have a variable "count" in javascript and a radio button that I want to depend on that variable. 我在javascript中有一个变量“count”和一个我希望依赖于该变量的单选按钮。 There is a button to generate more radio buttons, which is why I need their name attributes to differ. 有一个按钮可以生成更多单选按钮,这就是我需要它们的名称属性不同的原因。

My code: 我的代码:

var count = 1;
function newForm(){
...<input name=count type="radio" value="Website" />...
}

But it's just setting the name of each additional radio button to "count" rather than the number "count" represents. 但它只是将每个附加单选按钮的名称设置为“count”而不是“count”表示的数字。

Here's the whole code: 这是整个代码:

var count = 1;
function newForm(){
var newdiv = document.createElement('div');
newdiv.innerHTML = '<div class="line"></div><br><input type="text" name="Name" 
class="field" placeholder="Full Event Name" /><br><input type="text" name="Location"       
placeholder="Event Location" class="field" /><br> <input type="text" name="Date" 
placeholder="Event Date" class="field" /> <br> <input type="text" name="End" 
placeholder="Event End Date (If Applicable)" class="field" /> <br> <input type="text" 
name="Time" placeholder="Event Time" class="field" /> <br> <input type="text"     
name="Tags" 
placeholder="Relevant Tags" class="field" /> <br> The info is from: <input name=count 
type="radio" value="Tweet" checked="" />Tweet <input name=count type="radio"   
value="Website" 
/>Website <input name=count type="radio" value="Tweet and Website" /> Tweet and  
Website';
if(count < 10) {
    document.getElementById('formSpace').appendChild(newdiv);
    count++;
}

} }

That newdiv.innerHTML string above is all on one line in the code, by the way. 顺便说一句,上面的newdiv.innerHTML字符串都在代码中的一行上。

If you're trying to create an element, use createElement() : 如果您正在尝试创建元素,请使用createElement()

var count = 1;

function newForm(){
     var input = document.createElement('input');

     input.name  = count;
     input.type  = 'radio';
     input.value = 'Website';
}

in your long string of innerHTML you need to escape your "count" variable... otherwise it's just a string... ie 在你的longHTML长字符串中你需要转义你的“count”变量...否则它只是一个字符串...即

'<input name='+count+' type="radio" value="Tweet and Website" />';

That will make it work but as everyone else is mentioning - you really shouldn't embed long html strings like this. 这将使它工作,但正如其他人提到的那样 - 你真的不应该嵌入像这样的长html字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM