Set x.innerHTML as INPUT truncating value string
I have:
function 开发者_JS百科edit(recRef)
{
var recID=recRef+'_what';
var x=document.getElementById(recID);
var y=(x.innerHTML);
alert(y);
x.innerHTML="<INPUT type='text' value="+y+" />";
}
The original recID element is a TD with a string in it [e.g. "This string"].
At the end of calling the edit function the an INPUT tag type text is inside the TD tag, but the string is truncated to only the first word [e.g. in the example it shows "This" but not "This string"].
Even more interesting, if the string in the TD was originally empty after calling edit the value on the INPUT tag is a single forward slash "/".
What is going on here?
Try this code instead:
var recID = recRef+'_what';
var oRecord = document.getElementById(recID);
var sHTML = oRecord.innerHTML;
var oInput = document.createElement("input");
oInput.type = "text";
oInput.value = sHTML;
while (oRecord.childNodes.length > 0)
oRecord.removeChild(oRecord.childNodes[0]);
oRecord.appendChild(oInput);
This will directly insert new DOM element instead of messing with the literal HTML.
You forgot ' in the value attribute
x.innerHTML="<INPUT type='text' value='"+y+"' />";
Built atop Shadow's response, heres what a cross browser solution might look like
function edit(recRef) {
var isIE/*@cc_on=1@*/;
var el = document.getElementById(recRef);
var input = document.createElement( isIE ? "<input type='text'>" : "input" );
input.setAttribute("value",el.innerHTML)
el.replaceChild(input,el.childNodes[0]);
}
精彩评论