Concat two lines in jQuery

As in the title above: how to combine two lines in jQuery?

This is my code:

$(document).ready(function(){           
    serviceName = '<?=$_GET['services'] . ".php";?>';
    serviceID='<?= "#" .$_GET['services'];?>';
    serviceClass = '<?=$_GET['services'];?>';

    if (serviceName != "") {
        alert(serviceID);
        $('.main_content').load(serviceName);
        $(serviceID).addClass("it");
    }
});

As you can see in my previous code, in the variable name serviceID, I concatenate hashtagmy value GETas well, and I try to put it in ALERT, and the result will be correct, but when I assign it to it .addClassdoesn’t work.

Any alternatives and solutions are greatly appreciated.

+4
source share
3 answers

I assume that you meant that the PHP code should be evaluated before arriving at the client, so your code syntax is correct, but check that the following looks cleaner and also does not pollute the global JavaScript area (which is what var. .. for):

var serviceClass = '<?="{$_GET["services"]}";?>';
var serviceName = serviceClass+'.php';
var serviceId = '#'+serviceClass;

, , serviceId , .

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

, :

<script>
             $(document).ready(function(){              
                serviceName = '<? echo "./".$_GET["services"].".php";?>';
                serviceID   = '<? echo "#" .$_GET["services"];    ?>';
                serviceClass ='<? echo $_GET["services"];         ?>';

            console.log(serviceID);

                if(serviceName!=""){
                    alert(serviceID);
                    $('.main_content').load(serviceName);
                    $(serviceID).addClass("it");

                }
});
</script>

( firebug chrome), , .

+3

Try, but not sure, My change is added by "#"Id in jquery

<script>
             $(document).ready(function(){              
                serviceName = '<?=$_GET['services'] . ".php";?>';
                serviceID='<?= $_GET['services'];?>';
                serviceClass = '<?=$_GET['services'];?>';

                if(serviceName!=""){
                    alert(serviceID);
                    $('.main_content').load(serviceName);
                    $("#"+serviceID).addClass("it");

                }
});
</script>
0
source

Source: https://habr.com/ru/post/1538555/


All Articles