I need to change the width of a td using javascript. The value of the width will be pulled in and then I need to multiple it to get a percentage. I just need to know how to write the js so far I have got to here but it is not working
<script language="JavaScript">
var divWidth = 66*0.4;
document.write("<td width="+divWidth+">");
document.getElementById("myRow").write("<td width="+divWidth+">");开发者_StackOverflow社区
</script>
<table>
<tr>
<td id="myRow"></td>
</tr>
I think you want this:
<script type="text/javascript">
var divWidth = 66*0.4;
document.getElementById("myRow").setAttribute('width', divWidth);//defaults to pixels
//or if you really want this as a percentage
document.getElementById("myRow").setAttribute('width', divWidth+'%');//percent
</script>
<table>
<tr>
<td id="myRow"></td>
</tr>
</table>
However, there are some things I would adjust in your code. I changed the language attribute in the script tag (now deprecated) to a type="javascript"
. The id
on your TD element is myRow
I would change this to something reflecting the cell vs. the row.
Try using jQuery, it's a Javascript library/framework and what you're trying to do above will be ten times easier using jQuery.
With jQuery, your code will be:
$(document).ready(function () {
var newWidth = $("#myRow").width();
$("#myRow").width(newWidth*0.4);
}
//edit:
Sorry, I had the multiple wrong.
精彩评论