如上标题:如何在JQuery中连接两个字符串?
到目前为止,这是我的代码:
$(document).ready(function(){
serviceName = '<?=$_GET['services'] . ".php";?>';
serviceID='<?= "#" .$_GET['services'];?>';
serviceClass = '<?=$_GET['services'];?>';
if (serviceName != "") {
alert(serviceID);
$('.main_content').load(serviceName);
$(serviceID).addClass("it");
}
});
正如您在我上面的代码中看到的,在变量名 serviceID
中,我连接了 hashtag
和我的 GET
值,我尝试把它放在 ALERT 上,结果是正确的,但是当我将它分配给 .addClass
时,它不起作用。
非常感谢任何替代方案和解决方案。
最佳答案
我猜你的意思是 PHP 代码应该在到达客户端之前进行评估,因此你的代码语法是正确的,但检查下面看起来更干净并且也没有污染全局 JavaScript 范围(这就是 var ...是为了):
var serviceClass = '<?="{$_GET["services"]}";?>';
var serviceName = serviceClass+'.php';
var serviceId = '#'+serviceClass;
但是,由于你的代码语法是正确的,你应该验证你在执行它时确实有一个以 serviceId 作为 id 的元素
if (($(serviceId)||[]).length) {
alert('your element with the id:'+serviceClass+' exists');
}
else {
alert('your element with the id:'+serviceClass+' doesn\'t exists');
}
关于javascript - 在 JQuery 中连接两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23361027/