dtd58256 2017-04-11 19:58
浏览 70
已采纳

通过python脚本将php变量参数传递给onclink函数

I have been trying to call a onclick js function which contains a an argument in the form of PHP variable. My code looks something like this:

    echo "<input type = 'button' onclick = 'activateit(".json_encode($name).")' value = '$name'>";

But it gives the following error:

    activateit is not defined at HTMLInputElement.onclick

And the chrome inspect element shows it like this:

     onclick = 'activateit("chai")'

where $name = chai. I have been stuck on this for quite some time now. Please help.

  • 写回答

1条回答 默认 最新

  • drqvsx1228 2017-04-12 16:02
    关注

    As mentioned in the comments use the below to make things better you would assign your value to id or any attribute you want to call it and for each button added you use the class attribute so that you can have multiple buttons added without any problems and also to avoid having many click event declarations. Ofcoarse you would have to include your jquery script tag as well

    // echo "<input type = 'button' onclick = 'activateit(".json_encode($name).")' value = '$name'>"; is change to the below
    echo "<input type = 'button' id=".json_encode($name)." value = '$name' class='added_button'>";
    

    we then use $ (document).on because we want the event to be fired for any buttons that exists and also if there are more buttons added after the page loads

    $ (document).on ('click', '.added_button', function (e) {
        // this will be added if you dont want a form to submit when the button is pressed if it is in a form
        // or to stop it from doing whatever it was meant to do
        e.preventDefault (); 
    
        var name = this.id; // this will give you the value 'chai'
    
        // to test it we do an alert 
        alert (name);
    
    
        // add your code here
    });
    

    to include jquery use <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率