Php 如何将$variable插入jQuery
我在Drupal中与jQuery一起工作。如何将php$变量插入标记中Php 如何将$variable插入jQuery,php,jquery,drupal,Php,Jquery,Drupal,我在Drupal中与jQuery一起工作。如何将php$变量插入标记中 $(document).ready(function(){ $("#comment-delete-<?php print $variable ?>").click(function(){ $("div.comment-<?php print $variable ?> span.body").replaceWith("new text"); }); }) 有几件事需要澄
$(document).ready(function(){
$("#comment-delete-<?php print $variable ?>").click(function(){
$("div.comment-<?php print $variable ?> span.body").replaceWith("new text");
});
})
有几件事需要澄清。
我在Drupal中运行,因此完整代码如下所示:
<?php
drupal_add_js (
'$(document).ready(function(){
$("#comment-delete-"' print $comment->cid; ').click(function(){
$("div.comment-"' print $comment->cid; '" span.body").replaceWith("<span style=\'color: grey;\'>Please wait...</span>");
});
})',
'inline');
?>
但它仍然不起作用
更新:我尝试了以下方法,但仍然不起作用
<?php
$testing = "42";
drupal_add_js (
'$(document).ready(function(){
$("#comment-delete-"'. $testing .').click(function(){
$("div.comment-"'. $testing .'" span.body").replaceWith("<span style=\'color: grey;\'>Please wait...</span>");
});
})',
'inline');
?>
如果我使用数字42而不是变量,它会工作,但在使用变量时不会工作。。。奇怪
$(document).ready(function(){
$("#comment-delete-<?php print $variable ?>").click(function(){
$("div.comment-<?php print $variable ?> span.body").replaceWith("new text");
});
})
服务器将页面发送到浏览器
浏览器读取页面
Javascript运行:
如果您注意到了,PHP只是创建了要发送到浏览器的网页。因此,使用PHP所要做的就是创建Javascript代码。在PHP中工作时,实际上不必遵循任何Javascript语法规则。当Javascript进入浏览器时,您必须简单地使其语法正确。也就是说,你可以插入所有你想要的标签,只要当页面进入浏览器时,它是有效的Javascript
如果将代码传递到函数中,如注释所述,则将创建一个用引号封装的字符串,在这种情况下,第二个示例是正确的:
drupal_add_js (
'$(document).ready(function(){
$("#comment-delete-'. $variable . ').click(function(){
$("div.comment-'. $variable . ' span.body").replaceWith("<span style=\'color: grey;\'>Please wait...</span>");
});
})',
'inline');
根据您的评论:
<?php
drupal_add_js ('
$(document).ready (function() {
$("#comment-delete-' . $variable . '").click (function() {
$("div.comment-' . $variable . ' span.body").replaceWith ("new text");
});
})
','inline');
?>
您应该连接$variable,而不是打印它[edit]oops,没关系,我刚刚意识到确切的答案已经发布了,我只是没有足够仔细地遵循它。您尝试过吗?第一种方法应该适合你我在Drupal,我用的是“不介意”。。。那是行不通的。。。但是正如你所看到的,我已经在php中了,我无法退出以插入php变量。你有一些错误的引号。请单击我们答案旁边的复选框以将其标记为正确。Thnx!很高兴你的问题解决了。
$(document).ready(function(){
$("#comment-delete-mytag").click(function(){
$("div.comment-mytag span.body").replaceWith("new text");
});
})
$(document).ready(function(){
$("#comment-delete-mytag").click(function(){
$("div.comment-mytag span.body").replaceWith("new text");
});
})
drupal_add_js (
'$(document).ready(function(){
$("#comment-delete-'. $variable . ').click(function(){
$("div.comment-'. $variable . ' span.body").replaceWith("<span style=\'color: grey;\'>Please wait...</span>");
});
})',
'inline');
<?php
drupal_add_js ('
$(document).ready (function() {
$("#comment-delete-' . $variable . '").click (function() {
$("div.comment-' . $variable . ' span.body").replaceWith ("new text");
});
})
','inline');
?>