最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - document.getElementById(variable) Help! - Stack Overflow

programmeradmin0浏览0评论

I know it can be done but am having issues getting it to work. Basically I want to change the font color of a specific table cell based on a variable which changes daily, in effect highlighting the day of the week in a calendar. I know that a variable can be used to get the element id but what am I missing here? I have tried using a unique DIV inside each cell but get the same error - "Object Required". Thanks in advance. Here is the code:

<style>

td#day1{color:white;} td#day2{color:white;} td#day3{color:white;} td#day4{color:white;} etc..

<script type="text/javascript">
function calculate_date(){
    currentTime = new Date();
    day = currentTime.getDate();
    return day;
    }
function highlight_day() {
    calculate_date(); 
    today = 'day'+ day;
    document.getElementById(today).style.color= "red";
    }
document.onload(highlight_day());
</script>
</head>
<body>
SEPTEMBER
<table class="cal">
<tr>
<td id="day1">1</td><td id="day2">2</td><td id="day3">3</td><td id="day4">4</td>

I know it can be done but am having issues getting it to work. Basically I want to change the font color of a specific table cell based on a variable which changes daily, in effect highlighting the day of the week in a calendar. I know that a variable can be used to get the element id but what am I missing here? I have tried using a unique DIV inside each cell but get the same error - "Object Required". Thanks in advance. Here is the code:

<style>

td#day1{color:white;} td#day2{color:white;} td#day3{color:white;} td#day4{color:white;} etc..

<script type="text/javascript">
function calculate_date(){
    currentTime = new Date();
    day = currentTime.getDate();
    return day;
    }
function highlight_day() {
    calculate_date(); 
    today = 'day'+ day;
    document.getElementById(today).style.color= "red";
    }
document.onload(highlight_day());
</script>
</head>
<body>
SEPTEMBER
<table class="cal">
<tr>
<td id="day1">1</td><td id="day2">2</td><td id="day3">3</td><td id="day4">4</td>
Share Improve this question asked Sep 7, 2009 at 23:58 DaveDave 801 gold badge2 silver badges7 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 9

This function is incorrect:

function highlight_day() {
  calculate_date(); 
  today = 'day'+ day;
  document.getElementById(today).style.color= "red";
}

The 'day' variable is not set anywhere. You probably wanted this:

function highlight_day() {
  var day = calculate_date(); 
  var today = 'day'+ day;
  document.getElementById(today).style.color= "red";
}

Change this line:

calculate_date(); 

to:

var day = calculate_date();

The error you are getting is because 'day' does not exist within the current scope.

发布评论

评论列表(0)

  1. 暂无评论