简体   繁体   English

PHP动态变量作为jQuery选择器

[英]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: . jQuery抛出此错误: 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. 我研究了它,发现这是一个Sizzle错误,当jQuery找不到引用的选择器时会发生这种错误。 As was suggested in other questions on SO, this was not actually an error in my jQuery code, it was elsewhere. 正如其他关于SO的问题所建议的那样,这实际上并不是我的jQuery代码中的错误,而是在其他地方。

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: 我正在定义一个变量用作加载内容的目标元素,并使用PHP动态定义变量,如下所示:

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: 但是,用静态字符串替换PHP变量可以正常工作:

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. 在执行此操作之前,您可以尝试trim($target) 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. 还可以考虑使用json_encode将变量从php传递给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. 原来我加载的页面没有传递给它的变量$ target。 On the initial page, $target was initialized with a value, and thus the source output looked as specified in the question. 在初始页面上,使用值初始化$ target,因此源输出看起来像问题中指定的那样。 However, the ajax call I was making to reload the page with new data was not passing the variable. 但是,我正在使用新数据重新加载页面的ajax调用没有传递变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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