将PHP变量传递给onClick方法 [英] Passing PHP variable to onClick method

查看:84
本文介绍了将PHP变量传递给onClick方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP从MySQL中提取一些数据,并且需要将ID作为参数传递给onClick()方法.

I'm pulling some data from MySQL using PHP and need to pass an ID as a parameter to a onClick() method.

while($row = mysql_fetch_array($result))
{   
  echo '<a href=# onclick="showFilm('<?php echo $row['ID'] ?>')">' . 
    $row['Title'];
}

我在echo语句上遇到语法问题.我在做什么错了?

I'm getting a syntax issue on the echo statement. What am I doing wrong?

推荐答案

是的,您正在尝试在一行PHP中打开一个php标签.这样做

Yes you're trying to open a php tag inside a line of php. Do this

echo '<a href="#" onclick="showFilm(' . $row['ID'] .')">' . $row['Title'] . '</a>';

您还错过了结尾</a>.理想情况下,您不会使用onclick,但这不是您所要的,并且不会随它而中断.哦,应该引用href的值.

There's also a closing </a> you missed. Ideally you wouldn't use onclick but that's not what you asked about and it won't break with it there. Oh, and the value of href should be quoted.

因此,根据您的要求,假设您要使用jQuery而不是onclick

So, since you ask, let's say you wanted to use jQuery instead of onclick

echo '<a href="#" class="showfilm" data-filmid="' . $row['ID'] .'">' . $row['Title'] . '</a>';

您需要包括jquery库.请参见 http://docs.jquery.com/How_jQuery_Works ,并且在或在单独的js文件中.

You would need to include the jquery library. See this http://docs.jquery.com/How_jQuery_Works and you would need your own script before </body> or in a separate js file.

<!-- the rest of your html blah blah -->
<script src="jquery.js"></script>
<script src="your-other-js-funcs.js"></script>
<script>
$(function(){
    $('.showfilm').on('click', function(e){
        e.preventDefault(); // stops the link doing what it normally 
                            // would do which is jump to page top with href="#"
        showFilm($(this).data('filmid'));
    });
});
</script>
</body>
</html>

这篇关于将PHP变量传递给onClick方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆