dongtangyi8962 2015-01-06 16:01
浏览 73
已采纳

从PHP插入DOM的动态变量。 无法将该变量从DOM传递到Javascript

I'm trying to create a system where people can vote on answers to a question.

The answers are fetched from a database then displayed in a foreach.

For the voting system I need to pass certain variables into JS to the do some AJAX magic with, however i'm falling at the first hurdle of just passing the variables to JS.

At the moment the code looks like such:

<?php
            if ($answers->num_rows() == 0) {
                echo '<p>Be the first to answer this question!</p>';
            } else {
                foreach ($answers->result() as $row)
                {
                    echo '<div class="answers-to-question">';
                    echo '<form>'; //form for the purpose of voting
                    echo '<input type="hidden" name="a_id" value="'.$row->a_id.'">'; //pass this to voting script
                    echo '<input type="hidden" name="u_id" value="'.$row->username.'">'; //pass this to voting script
                    echo '<pre>'.$row->answer.'</pre>';
                    echo '<p class="green">answered '.$row->timestamp.' by <i class="green">'.$row->username.'</i></p>';
                    echo '<input type="button" name="upvote" value="upvote" onClick="upvote(this.form.u_id);">';
                    echo '</form>';
                    echo '</div>';

                }
            }               
            ?>

So I have a button which on click should pass the variables in a JS function

Button

echo '<input type="button" name="upvote" value="upvote" onClick="upvote(this.form.u_id);">';

Javascript

$(document).ready(function(){

        function upvote(username){

            console.log(username);

        }
    });

This isn't working and i'm getting the error:

Uncaught TypeError: object is not a function   onClick

If it helps, i'm using the Codeigniter and JQuery frameworks

Any help greatly appreciated

  • 写回答

2条回答 默认 最新

  • duanlei20082008 2015-01-06 16:11
    关注

    Do it all with jQuery instead of using inline JavaScript -

    $(document).ready(function(){
    
        function upvote(username){
            console.log(username);
        }
    
        $('input[name="upvote"]').click(function() {
            var username = $(this).parent('form').find('[name="u_id"]').val();
            upvote(username);
        });
    });
    

    EXAMPLE

    Here is an UPDATE sending two variables to the function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?