是否可以在您的js代码中插入php变量? [英] Is it possible to insert php variables into your js code?
问题描述
可能重复:
将变量从php传递到javascript
Possible Duplicate:
passing variables from php to javascript
我正在动态生成一个列表.我想使每行都悬停在鼠标悬停上并单击链接.我希望链接传递行内容的ID.
I'm dynamically generating a list. I want to make each row hover on mouseover and clickable to a link. I want the link to pass the id of the content of the row.
基本上:
foreach ($courses as $cid=>cinfo){
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print "<div class='rc_desc' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
}
<script>
$(function ()
{
$('#rc_desc$cid').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?$cid');
});
});
</script>
问题出在js/jquery中.我希望能够抓住$ cid并在单击后将其传递给student.php页面.上面的php代码有效,但是js当然不会.我知道客户端语言和服务器端语言的基本知识.这个问题不值得上课.我知道我不能完全做到这一点,但这是我最终想要实现的目标.关于如何可以简单地实现这一目标的任何想法?预先感谢我的朋友们!
The issue is in the js/jquery. I want to be able to grab the $cid and pass it to the student.php page upon click. The php code above works but the js won't of course. I know the fundamental of client-side vs server-side languages. This question doesn't warrant a lecture. I know I cannot do this exactly, but it is what I want to happen ultimately. Any thoughts on how I can achieve this simply? Thanks in advance my friends!
推荐答案
是的,如果您在PHP代码中包含<script>
部分,则可以执行以下操作:
Yes, if you include the <script>
section in your PHP code, you can do something similar to the following:
<script>
var foo = <?php echo $foo; ?>;
</script>
对于您而言,您将研究以下代码结构:
In your case, you would be looking into the following code structure:
<script>
$(function () {
$('#rc_desc<?php echo $cid ?>').hover(function () {
$(this).toggleClass('.tr');
});
$('#rc_desc<?php echo $cid ?>').click(function () {
$(location).attr('href', 'student.php?<?php echo $cid ?>');
});
});
</script>
之所以可行,是因为尽管Javascript是在客户端运行的,但在页面上展示之前,它先在服务器端进行了处理.因此,它将用您包含的实例替换$cid
的所有必要实例.
The reason why this is possible is because although the Javascript is run on the client-side, it's processed on the server-side first prior to being presented on the page. Thus, it'll replace all necessary instances of $cid
with the one you have included.
祝你好运!
编辑:
<script>
$(function () {
$('.rc_desc').hover(function () {
$(this).toggleClass('.tr ');
});
$('.rc_desc').click(function () {
$(location).attr('href', 'student.php?' + $(this).attr('id').split('rc_desc')[1]);
});
});
</script>
这篇关于是否可以在您的js代码中插入php变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!