连接变量作为选择器不起作用(Javascript/Jquery)
我很困惑&对 jQuery 相当缺乏经验。我试图将一个值从厚盒窗口传递回父页面上的输入元素。为了确定正确的输入框,我尝试连接两个值,其中一个值是我成功从厚盒窗口中获取的,另一个值是一段文本,如下例所示。
grab_flavor = $('#flavor').val(); //contains 'apple'
alert(grab_flavor); // returns 'apple'
juice = "#" + grab_flavor + "juice";
alert(juice); // returns '#applejuice'
$(juice , top.document).val("favorited"); //doesn't seem to work...
flavor = "#apple";
juice = flavor + "juice";
$(juice , top.document).val("favorited"); // works
我似乎无法弄清楚为什么第一个串联不起作用,即使当我用警报显示它时它返回正确的值,但什么也没有发生。
我尝试了多种不同的连接方法,但是当我尝试包含“grabflavor”时,它们都失败了......非常感谢建议!
更新:正在研究一个更好的实时示例...
更新 2(最终):弄清楚了...语法毕竟是有效的,连接没有任何问题,我只是忽略了一个小细节,因为我正在处理看起来相同的很长的选择器......下次我会休息更长的时间,这样我就可以从新的眼睛中受益。固执地执着于理解问题并不总是那么有效。感谢评论者发帖并指出 jsfiddle 和 jsbin,这是两个非常有用的发现!
I'm puzzled & pretty unexperienced with jQuery. I'm trying to pass back a value from a thickbox window into an input element on the parent page. To determine the right input box I'm trying to concatenate two values, one of which I successfully grab from the thickbox window and the other value is a piece of text, like example below.
grab_flavor = $('#flavor').val(); //contains 'apple'
alert(grab_flavor); // returns 'apple'
juice = "#" + grab_flavor + "juice";
alert(juice); // returns '#applejuice'
$(juice , top.document).val("favorited"); //doesn't seem to work...
flavor = "#apple";
juice = flavor + "juice";
$(juice , top.document).val("favorited"); // works
I can't seem to figure out why the first concatenation isn't working, even though it returns the right value when I display it with an alert, instead nothing happens.
I've tried a number of different ways to concatenate, but they all fail when I try to include 'grabflavor'...advice much appreciated!
update: working on a better live example...
update 2 (final): figured it out...syntax was valid after all, nothing wrong with the concatenation, I just overlooked a small detail because I was dealing with very long selectors that looked the same...next time I will take a longer break so I can benefit from fresh eyes. Stubbornly obsessing to understand a problem doesn't always work so well. Thank you commenters for posting and pointing out jsfiddle and jsbin, two incredibly useful finds!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除非是转录过程中的另一个拼写错误,否则问题就在这里:
您缺少
grab_flavor
中的下划线。纠正它,它就可以工作了(实时复制)。Unless it's another typo during transcription, the problem is here:
You're missing the underscore in
grab_flavor
. Correct that, and it works (live copy).