繁体   English   中英

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

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

我在javascript中有一个变量“count”和一个我希望依赖于该变量的单选按钮。 有一个按钮可以生成更多单选按钮,这就是我需要它们的名称属性不同的原因。

我的代码:

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

但它只是将每个附加单选按钮的名称设置为“count”而不是“count”表示的数字。

这是整个代码:

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++;
}

}

顺便说一句,上面的newdiv.innerHTML字符串都在代码中的一行上。

如果您正在尝试创建元素,请使用createElement()

var count = 1;

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

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

在你的longHTML长字符串中你需要转义你的“count”变量...否则它只是一个字符串...即

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

这将使它工作,但正如其他人提到的那样 - 你真的不应该嵌入像这样的长html字符串。

暂无
暂无

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

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