admin管理员组

文章数量:1357276

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+">");

</script>


<table>
<tr>
    <td id="myRow"></td>
</tr>

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+">");

</script>


<table>
<tr>
    <td id="myRow"></td>
</tr>

Share Improve this question asked Sep 6, 2010 at 17:13 kristinakristina 611 gold badge1 silver badge2 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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.

本文标签: javascriptdynamical change td width with jsStack Overflow