tim99 tim99 - 4 months ago 14
CSS Question

Append a string with quotes from PHP to jQuery

i want to append a sting with quotes (eg.

< span class='MyClass'>
) to some jQuery Elements, which are stored in a database. This snippet works as i want.

<script>
$(document).ready(function() {
<?php
$result = mysql_query("SELECT concat(year(`wann`), lpad(month(`wann`),2,0), lpad(day(`wann`),2,0)) as wann, `wieviel` FROM `zecken`");
while($row = mysql_fetch_array($result)) {
for($i=1; $i <= $row["wieviel"]; $i++) {
?>

$('#<?php echo $row["wann"]; ?>').append("<span class='descr bg-danger'>1</span>");

<?php
}
}
?>
});
</script>


I just want to write in completely in PHP, and it also works if i delete the css-classes "descr bg-danger" from the span. Without css-classes my solution would be:

<script>
$(document).ready(function() {

<?php
$result = mysql_query("SELECT concat(year(`wann`), lpad(month(`wann`),2,0), lpad(day(`wann`),2,0)) as wann, `wieviel` FROM `zecken`");
while($row = mysql_fetch_array($result)) {
for($i=1; $i <= $row["wieviel"]; $i++) {

// How to add a class to this appended span ?????
echo "$('#".$row["wann"]."').append('<span >1</span>'); ";
}
}
?>

});
</script>


If i have to escape some quotes, how do i have to do this?
It's like i would need a third pair of different quotes for the span: ;)

echo "$('#".$row["wann"]."').append('<span class='''descr bg-danger'''>1</span>'); ";

Answer
echo "$('#".$row["wann"]."').append('<span class=\\'descr bg-danger\\'>1</span>'); ";

or, as @Andi North mentioned:

echo "$('#".$row["wann"]."').append('<span class=\"descr bg-danger\">1</span>'); ";

(The difference between the two is that one outputs class=\'... and one outputs class=".... Either should be perfectly valid JavaScript.)