简体   繁体   中英

proper way of using variables in html tags

I am always confused when it comes to use variables (php or js) in html tags. Most of my time is wasted on it while coding. Searched on the internet but it is covered nowhere in every aspect.

var variableToUse;

elem.append('<input type="text" value="variableToUse">');
elem.append('<div class="variableToUse" style="background-color: variableToUse">variableToUse</div>');

and in case of php

$variableToUse;

$query = "SELECT $variableToUse, $variableToUse, $variableToUse FROM table WHERE name=$variableToUse and email=$variableToUse";
elem.append('<input type="text" value="$variableToUse">');
elem.append('<div class="$variableToUse" style="background-color: $variableToUse">$variableToUse</div>');

These are some scenarios where I am always confused, if you can explain that would be really helpful. Or if you can give more examples or possible scenario.

In PHP, you use a . between variables and strings; the strings are embedded in quotation marks:

<?php 
$variable = "Morning";
echo "Good ".$variable; ?>
?>

...will result in "Good Morning"

In JS, the variables are NOT in quotation marks and instead of . you use + to connect variables and strings

<script>
var variable = "Morning";
var complete_name = "Good" + variable;
</script>

However, in JS there is no "echo" functionality.


ADDITIONAL STUFF (EDITED): As @Chris O'Kelly wrote, just treat HTML links in JS like regular strings:

PHP:

<?php echo '<input type="text" value='.$yourvariable.'">'; ?>

JS:

<script>elem.append('<input type="text" value="' + yourvariable + '">');</script>

(spaces around + can also be omitted)

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