douqianke7467 2014-05-13 10:25
浏览 23
已采纳

onClick监听器没有调用JavaScript [关闭]

I have an onClick listener set to trigger an AJAX call which in turn triggers a PHP script. However, it doesn't seem to recognize the click. Any ideas?

Index.html

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function doThings(){
    document.write("Test");
    $.ajax( {
    type: "GET",
    url: "script.php",
    success:function(data){
    if(data==0)
        $("#imgId").attr("src","lightbulb_0.png");
    else
        $("#imgId").attr("src","lightbulb_1.png");
    }
    });
}
</script>
</head>
<body>
<img id="imgId" src="lightbulb_0" onClick='doThings();'/>
</body>
</html>

Script.php

<?php
function toggle()
{
        $filename = "brightness";
        $otherDirectory="/sys/class/leds/led0/";
        $f = fopen($otherDirectory . $filename,"r");
        $value = fgets($f);
        $newvalue = 1;
        fclose($f);
        if ((int)$value == 1) {
           $newvalue = 0;
        }

        if ((int)$value == 0) {
           $newvalue = 1;
        }

        $f = fopen($otherDirectory . $filename,"w+");

        fwrite($f, $newvalue);

        fclose($f);

        echo $newvalue;

}
toggle();
?>

EDIT: Added code on here, and used fix from below. Now the onClick() works, but after setting the image to lightbulb_1, it won't go to 0.

EDIT2: Fixed using combination of all solutions below. Thanks alot!

  • 写回答

3条回答 默认 最新

  • douwulu2576 2014-05-13 10:28
    关注

    Add Separate <script> tag for including js files and code. Use below code,

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
    function doThings(){
        //Your function code
    }
    </script>
    
    //Html codes
    <img id="imgId" src="lightbulb_0" onClick='doThings();'/>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置