如何使用php中的onclick事件属性动态创建链接标记
问题描述:
I'm trying to make Href tag in php like this :
while($row = mysql_fetch_array($result))
{
echo"<a href >".$row['loginname']."<br>"."</a> ";
}
which retrieve the data from MySQL
I'm trying to add Onclick
action to print $row['loginname']
I tried to make this one
echo"<a href onclick=\"myFunction()\">".$row['loginname']."<br>"."</a> ";
function myFunction()
{
echo " Hello";
}
but It didn't work for me ? any help ?
答
Assuming my comment is accurate, you would need to print the JavaScript to the page.
echo "<a href onclick=\"myFunction()\">".$row['loginname']."<br>"."</a> ";
$js = '<script type="text/javscript">';
$js .= 'function myFunction() { alert("hello"); }';
$js .= '</script>';
echo $js;
Notice I removed echo
, as that is not JavaScript. You can look into something like document.write()
答
<?php
while($row=mysql_fetch_array($result))
{
?>
<a href="" onclick="fetchdata('<?php echo $row['loginname']; ?>');"><?php echo $row['loginname']; ?></a>
<?php
}
?>
<script type="text/javascript">
var name;
function fetchdata(name){
alert(name);
}
</script>
You can use jquery ajax method to fetch further values from mysql database