Passing PHP variable to onClick method

2019-08-27 04:17发布

问题:

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();
});