连接变量作为选择器不起作用(Javascript/Jquery)

发布于 2024-10-30 21:07:19 字数 804 浏览 2 评论 0原文

我很困惑&对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

波浪屿的海角声 2024-11-06 21:07:19

除非是转录过程中的另一个拼写错误,否则问题就在这里:

juice = "#" + grabflavor + "juice";

您缺少 grab_flavor 中的下划线。纠正它,它就可以工作了(实时复制)。

Unless it's another typo during transcription, the problem is here:

juice = "#" + grabflavor + "juice";

You're missing the underscore in grab_flavor. Correct that, and it works (live copy).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文