我正在使用jQuery在Drupal中工作.如何将php $变量插入标记中.
$(document).ready(function(){
$("#comment-delete-<?php print $variable ?>").click(function(){
$("div.comment-<?php print $variable ?> span.body").replaceWith("new text");
});
})
Run Code Online (Sandbox Code Playgroud)
要么
$(document).ready(function(){
$("#comment-delete-". $variable).click(function(){
$("div.comment-". $variable ." span.body").replaceWith("new text");
});
})
Run Code Online (Sandbox Code Playgroud)
要澄清一些事情.我在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');
?>
Run Code Online (Sandbox Code Playgroud)
但它仍然无法正常工作.
更新:我尝试了以下,但它仍然无法正常工作
<?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');
?>
Run Code Online (Sandbox Code Playgroud)
如果我使用数字"42"而不是变量,它可以工作,但不是在使用变量时......很奇怪.
$(document).ready(function(){
$("#comment-delete-<?php print $variable ?>").click(function(){
$("div.comment-<?php print $variable ?> span.body").replaceWith("new text");
});
})
Run Code Online (Sandbox Code Playgroud)
因为PHP在页面加载之前执行,所以第二种方法不起作用.实际上,第二个混合了两种在不同时间运行的不同语言,这意味着......它仍然不起作用.
这就是发生的事情.
浏览器请求页面
PHP创建HTML页面
PHP在文件中搜索<?php ?>
标签,并在其中运行代码:
$(document).ready(function(){
$("#comment-delete-<?php print $variable ?>").click(function(){
$("div.comment-<?php print $variable ?> span.body").replaceWith("new text");
});
})
Run Code Online (Sandbox Code Playgroud)
以上示例将在解析后创建:
$(document).ready(function(){
$("#comment-delete-mytag").click(function(){
$("div.comment-mytag span.body").replaceWith("new text");
});
})
Run Code Online (Sandbox Code Playgroud)
服务器将页面发送到浏览器
浏览器读取页面
Javascript运行:
$(document).ready(function(){
$("#comment-delete-mytag").click(function(){
$("div.comment-mytag span.body").replaceWith("new text");
});
})
Run Code Online (Sandbox Code Playgroud)
如果您注意到,PHP只是创建要发送到浏览器的网页.所以你用PHP做的就是创建Javascript代码.在PHP中工作时,您实际上不必遵循任何Javascript语法规则.您必须在访问浏览器时简单地使Javascript语法正确.AKA您可以插入所需的所有<?php ?>
标签,只要页面到达浏览器时,它就是有效的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');
Run Code Online (Sandbox Code Playgroud)