向onclick事件发送php变量


sending a php variable to onclick event

我可以使用类似的链接的onclick事件将php变量发送到我的javascript函数吗

<a onclick="change(<?php echo $description ?>)">

当我回显描述时,它是可用的,但当我将其发送到javascript函数时,它会显示未定义的

我该怎么做?

感谢

$description可能是一个字符串,因此您需要在Javascript中用引号括起来:

<a onclick="change('<?php echo $description ?>')">

您可以在jquery中轻松完成此操作。。如果您有兴趣使用另一个库,如jquery。。

Js

var description;
$('#description').click(function(){
  description = $(this).val();
  //alternatively you can use data-description and retrieve it like so:
  description = $(this).data('description');
  //if that doesnt work use attr();
  description = $(this).attr('data-description');
  //this will return "My awesome description"
  console.log(description);
}

php

<?php 
$description = 'My awesome description';
?>

html

<a id="description" href="#"><?= $description; ?></a>
<!-- alternatively you could used data-description attribute on the href and pass that.. -->
<a href="#" data-description="<?= $description; ?>">Link 1</a>