在JQuery中连接两个字符串

Unk*_*ous 6 javascript jquery

就像上面的标题:如何在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");
    }
});
Run Code Online (Sandbox Code Playgroud)

正如你在上面的代码中看到的,在变量名中serviceID,我连接hashtag和我的GET值,我尝试将它放在ALERT上,结果是正确的,但是当我分配给它时.addClass它不起作用.

非常感谢任何替代方案和解决方案.

Mar*_*man 11

我猜你的意思是在到达客户端之前应该评估PHP代码,因此你的代码语法是正确的,但是看看下面看起来更清晰,也没有污染全局JavaScript范围(这就是var ...的用途) :

var serviceClass = '<?="{$_GET["services"]}";?>';
var serviceName = serviceClass+'.php';
var serviceId = '#'+serviceClass;
Run Code Online (Sandbox Code Playgroud)

但是,由于您的代码语法是正确的,您应该验证在执行它时实际上是否有一个带有serviceId的元素作为id

if (($(serviceId)||[]).length) {
    alert('your element with the id:'+serviceClass+' exists');
}
else {
    alert('your element with the id:'+serviceClass+' doesn\'t exists');
}
Run Code Online (Sandbox Code Playgroud)