Is it possible to assign a class from a php variable to a new appended div in jquery?
$newItems = $('<div class="PHP VARIABLE PRINTS HERE A CLASS"></div>');
In my case, for other things, I am defining a var to defign what I then append in jquery but I need to get the class of the newly inserted div from a php variable. Is it possible?
In PHP
<?php
// First you need to have the variable with the name of classe
$myClass = 'name_of_my_classe';
?>
In Javascript:
$newItems = $('<div class="<?php echo $myClass; ?>"></div>');
There are two different ways I would imagine doing this.
Firstly you could use Ajax to get the variable earlier on, from the php variable, or you could simply echo the variable there inline from a function within the file.
The first way of doing this, using Ajax, is perhaps a more standard way of doing this, whereas I would count the latter method as a little bit quick and dirty.
I think that hardcore mixing of PHP and JavaScript code is an anti-pattern and can lead to confusion. I would limit PHP emissions to build HTML and use the JavaScript code to parse said HTML to get your desired client result:
//php
echo '<span hidden id=class-container data-class=name_of_my_class>';
//JavaScript
$("<div>").addClass($("#class-container").data('class'));
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.