问题
I have an input box on a html page. I know I can get just the value, but I want the entire input string, i.e. , but with the value present:
<input id="myInput" value="my entry that I just typed in"/>
I have tried innerHTML, I have tried XMLSerializer, etc.
var htmlDiv = document.getElementById('myInput');
var str = s.serializeToString(htmlDiv);
The value is always empty.
If you are wondering why I want to do this - it is because this is my simple example of what in reality is about 60 inputs, all part of an HTML string that I want to send to XSLT translation. That part works like gangbusters, I just have to get it HTML with values intact.
Another related problem is that innerHTML has a nasty habit of getting rid of the / at the end of the input box, which throws off the XSLT translation.
回答1:
Try this:
console.log(document.getElementById("myInput").outerHTML);
<input id="myInput" value="my entry that I just typed in"/>
myVar = document.getElementById("myInput").outerHTML;
if(myVar.charAt(myVar.length - 1) !== "/"){
console.log(myVar.slice(0, myVar.length-1) + "/>");
}
<input id="myInput" value="my entry that I just typed in"/>
回答2:
I ended up doing the following: Serializing with XMLSerializer, which solved the / problem. And I just got the values from the DOM and inserted them myself.
function htmlCleanup(htmlDiv) {
//serialize the html. It will lack the latest user changes in the inputs.
var s = new XMLSerializer();
var str = s.serializeToString(htmlDiv);
var lines = str.split("\n");
//get all of the inputs in the div
var inputs = htmlDiv.getElementsByTagName('input');
//Here we put in the latest values
var inputIndex = 0;
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim();
if (line.indexOf('<input') >= 0) {
var value = inputs[inputIndex].value;
lines[i] = fixInputValue(line, value);
inputIndex++;
}
}
str = lines.join('\n');
//Some other weird aftertaste stuff that needs fixing. <tbody> is added to tables - wrongly.
//the div at the top is also a problem.
//Then we turn it all into proper xhtml for the trip back to the server.
var contents = str.replace('<div xmlns="http://www.w3.org/1999/xhtml" id="documentEditBody">', '');
contents = contents.replace(/<tbody>/g, '');
contents = contents.replace(/<\/tbody>/g, '');
contents = '<?xml version="1.0" encoding="UTF-8"?><html><head></head><body><div>' + contents + '</body></html>';
return contents;
}
function fixInputValue(input, value) {
var valuePos = input.indexOf('value');
var result = "";
if (valuePos > -1) {
for (var i = valuePos + 7; i < input.length; i++) {
var chr = input[i];
if (chr === '"') {
var last = input.substring(i + 1, input.length)
result = input.substring(0, valuePos - 1) + ' value="' + value + '" ' + last;
break;
}
}
}
return result;
}
来源:https://stackoverflow.com/questions/45089623/html-input-getting-the-value-via-innerhtml-or-xmlserializer