简体   繁体   中英

Display “Name” in case url parameters are absent

I am not sure whether this is right, but I request for your help where possible.

Below is my code. It displays the url parameters but in case of no parameters, its blank insted of displaying "Name"

<script>  
{
    var str = document.getElementById("id1").innerHTML; 
    var res = str.replace(/Name/gi, "<?php echo $_GET['n'];  ?>");    
    document.getElementById("demo").innerHTML = res;
}
</script>

<p id="id1">Name</p>

Because you are changing all the HTML inside the demo id tag.

<div id="demo"> Name</div>

If res = 'My';

document.getElementById("demo").innerHTML = res;

Result

<div id="demo">My</div>

Above line will overide any data inside id demo element with you definded HTML.

You only need to replace it if the query parameter exists. If not, just use the original:

var str = document.getElementById("id1").innerHTML; 

<?php if (isset($_GET['n'])) : ?>
    str = str.replace(/Name/gi, "<?= $_GET['n'] ?>");
<?php endif ?>

document.getElementById("demo").innerHTML = str;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM