[英]jQuery selector with injected PHP variable returns nothing
I'm experiencing the weirdest problem I've ever met. 我遇到了我遇到过的最奇怪的问题。 This has worked a thousand times before, but now I simply hit a wall on this seemingly impossible-to-solve problem. 这已经进行了上千次,但是现在我只是碰到了这个看似无法解决的问题。
I have a custom data-attribute on an element: 我在元素上有一个自定义数据属性:
<a href="#" data-pbid="5">My anchor</a>
I'm targeting this and alerting the amount of elements found: 我针对此目标,并警告发现的元素数量:
var myAnchor = $("a[data-pbid=5]");
alert(myAnchor.length) //Alerts "1".
However, when I change this to an injected PHP variable, it just doesnt work: (Im mixing a bit of code together here, but you know what's what.) 但是,当我将其更改为注入的PHP变量时,它将无法正常工作:(我在此处将一些代码混合在一起,但是您知道这是什么。)
var_dump($pbid); //returns string(1):"5"
<a href="#" data-pbid="<?php echo $pbid?>">My anchor</a>
var myAnchor = $("a[data-pbid=<?php echo $pbid?>]");
alert(myAnchor.length) //Alerts "0".
What on earth is going on here? 这到底是怎么回事?
Thanks in advance, 提前致谢,
Rasmus Dencker 拉斯穆斯·登克(Rasmus Dencker)
It may be because of a missing semicolon or the lack of the space between your variable and PHP end tag. 可能是因为缺少分号或变量与PHP结束标记之间没有空格。 Change this 改变这个
<a href="#" data-pbid="<?php echo $pbid?>">My anchor</a>
to <a href="#" data-pbid="<?php echo $pbid; ?>">My anchor</a>
<a href="#" data-pbid="<?php echo $pbid?>">My anchor</a>
到<a href="#" data-pbid="<?php echo $pbid; ?>">My anchor</a>
I found an answer to this. 我找到了答案。 In the OP I forgot to mention the fact that the elements were loaded and injected through ajax, and without explicitly setting the variable I somehow had a bit of a lag between the generation and the execution of the code. 在OP中,我忘了提到通过ajax加载和注入元素的事实,并且没有显式设置变量,我在代码的生成和执行之间就有点滞后了。 As a temporary hack I just put in a 作为临时的技巧,我只是在
setTimeout(function(){
//the stuff that had to be done
}, 500);
Thanks for your willingness to help! 感谢您的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.