Passing PHP variable to onClick method

蹲街弑〆低调 提交于 2020-01-06 09:58:16

问题


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'];
}

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


回答1:


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>';

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.

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>';

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>



回答2:


Another way:

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

Dont forget to close the a tag at the end. Didn't see it in your code.




回答3:


Your HTML

<?php while($row = mysql_fetch_assoc($result)): ?>
    <a href="#showFilm" data-film-id="<?php echo $row['ID'] ?>">
        <?php echo $row['Title'] ?>
    </a>
<?php endwhile ?>

Your jQuery

$('a[href=#showFilm]').click(function(event) {
    showFilm( $(this).attr('data-film-id') );
    event.preventDefault();
});


来源:https://stackoverflow.com/questions/13575561/passing-php-variable-to-onclick-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!