我正在创建一个动态输入元素,我想为它设置标签…我试过很多方法……
//get the value from the input
var getValue = $('#newField').val();
//create new input and set default value
var newField = document.createElement("input");
newField.setAttribute("type", "text");
newField.setAttribute("name", "s[x]np");
newField.setAttribute("id", "sx");
newField.setAttribute("class", "st form-text");
newField.setAttribute("value", getValue);
$('#addithere').append(newField);
//I've tried all of the following:
newField.prepend("Label");
...
newField.before("Label");
...
$('#sx').prepend("Label");
...
$('#sx').before("Label");
...
var secondItem = "Section: "+newField;
$('#addithere').append(secondItem);
$ (# sx) .prepend("标签");
这不是创建新标签元素的正确语法。你应该使用这样的代码:
$('#sx').prepend($('<label/>'));
何不试试$(newField).before('<label>Your label</label>');
?
编辑:也许你没有$(document).ready(function(){....});
我试过你的代码,没有这个-它不起作用…但有了它,它就成功了!
$(document).ready(function(){
var getValue = $('#newField').val();
var newField = document.createElement("input");
newField.setAttribute("type", "text");
newField.setAttribute("name", "s[x]np");
newField.setAttribute("id", "sx");
newField.setAttribute("class", "st form-text");
newField.setAttribute("value", getValue);
$('#addithere').append(newField);
$(newField).before('<label>Label</label>');
var secondItem = "Section: "+newField;
$('#addithere').append(secondItem);
});