简体   繁体   中英

PHP dynamic variable as jQuery selector

After hours of frustration, I finally found the line of code that has been causing an error, but now I need to know why.

jQuery was throwing this error: Uncaught Error: Syntax error, unrecognized expression: .

I've researched it and found that this is a Sizzle error that occurs when jQuery cannot find the selector that is referenced. As was suggested in other questions on SO, this was not actually an error in my jQuery code, it was elsewhere.

I was defining a variable to use as a target element to load content, and was using PHP to dynamically define the variable, like so:

var $container = $(".<? echo $target ?>");

This did not work, as the . is flagged as an unrecognized expression. However, replacing the PHP variable with a static string works fine:

var $container = $(".target");

This was so hard for me to find because I couldn't pinpoint the line that was throwing the error, and in the source from the browser, the initial line above looks just like the second line.

Why does the first example not work? Does it have to do with order of execution? And, how can I use a dynamic variable as a selector?

you have to use

<?php echo $test; ?>

or the shortcut:

<?= $test ?>

You can try trim($target) before doing this. If it works you probably have some unwanted spaces in that variable of yours.

Also consider using json_encode to pass variables from php to javascript. Like so:

var selector = <?php echo json_encode($target); ?>;
var $container = $(selector);

This will allow you to pass not only simple strings but more complex variable structures as well (and with encoding safety).

Turns out the page I was loading wasn't having the variable $target passed to it. On the initial page, $target was initialized with a value, and thus the source output looked as specified in the question. However, the ajax call I was making to reload the page with new data was not passing the variable.

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