Javascript: add attribute in for ... in statement
When I use here the direct ".attribute" form in the inner for-loop (commented line) it doesn't work. How do I have to rewrite the commented line to get the direct ".attribute" form working?
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
function dis开发者_如何转开发playResult()
{
var data = {
menge : { type : 'number', value : 5, size : "40" },
bezeichnung : { type : 'text', value : 'Kuchen', size : "80" },
euro_stueck : { type : 'text', value : 13, size : "40" } };
var table_id = "product";
var table = document.getElementById( table_id );
var rows = table.getElementsByTagName( 'tr' ).length;
var tr = table.insertRow( rows );
for ( name in data )
{
var td = document.createElement( 'td' );
var input = document.createElement( 'input' );
input.name = name;
for ( attr in data[name] )
{
//input.attr = data[name][attr]; <---
input.setAttribute( attr, data[name][attr] );
}
td.appendChild( input );
tr.appendChild( td );
}
}
</script>
</head>
<body>
<table id="product">
</table>
<br />
<form>
<input type="button" onclick="displayResult()" value="OK" />
</form>
</body>
</html>
Your question is a bit unclear, but I think you just need to use bracket notation, as you do elsewhere:
for (attr in data[name])
{
input[attr] = data[name][attr]; // <---
input.setAttribute( attr, data[name][attr] );
}
精彩评论