dongyi7513 2013-09-24 15:14 采纳率: 100%
浏览 15
已采纳

Javascript错误“Null不是对象”,带有动态创建的html表

I have a dynanamically created html table with a picture in the last cell of each row (like.png). What I would like to achieve is after the user has clicked on this picture another one is diplayed (like1.png). However I keep getting "Null is not an Object", there is maybe something wrong with my javascript code ...

Thank you for your help :)

Here is my php that creates the table :

<?php
$pictureid = 1;

            while($results = mysql_fetch_array($raw_results)){
            // $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop

            echo '<tr>';
            echo'<td>'. ucfirst($results['song_name']).'</td>';
            echo'<td>'. ucfirst($results['song_artist']).'</td>';
            //echo'<td>'. ucfirst($results['song_album']).'</td>';

                echo '<td>';

                echo  '<img src="images/like.png" id="artist'.$pictureid.'" onClick="action(artist'.$pictureid.')"/></a>';
                echo '</td>'; 
                echo '</tr>';

                $pictureid = $pictureid + 1;

                }

And here is my javascript :

<script language="javascript">
   function action(imageid)
{
if(document.getElementById(imageid).src == 'like.png' )
document.getElementById(imageid).src = 'like1.png';
else
document.getElementById(imageid).src = 'like1.png';
}
</script>          
  • 写回答

1条回答 默认 最新

  • duanna2026 2013-09-24 15:16
    关注

    You're missing some quotes here:

    echo  '<img ... onClick="action(\'artist'.$pictureid.'\')"/></a>';
    // quotes missing here ----------^---------------------^
    

    In your output HTML it should currently look like, e.g., this:

    <img ... onClick="action(artist1)"/>
    

    This would call the method action() and use a variable of the name artist1, which does not exists. So in your method document.getElementById() returns null and you get the error.

    Your method, however, requires a string input and thus you should enclose the parameter with quotes, so that it generates output like this:

    <img ... onClick="action('artist1')"/>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题