使用 JQuery 定位隐藏字段
归结为最简单的元素,我只想在单击页面上的元素时设置隐藏字段的值。
HTML:
<div id="toggleParent">
<input type="hidden" name="toggleValue" id="toggleValue" value="closed" />
<h2>Click Me</h2>
</div>
jQuery:
jQuery(document).ready(function() {
var toggle;
jQuery('div#toggleParent h2').click(function () {
if (toggle == '' || toggle == 'open') {
toggle = 'closed';
} else {
toggle = 'open';
}
jQuery('div#toggleParent input#toggleValue').val(toggle);
});
});
显然,它不起作用。 (否则我为什么会在这里?)点击事件工作正常,因为我可以在 Firebug 中单步执行它。但是当开始设置该值时,代码失败了。更重要的是,尝试 alert(jQuery('div#toggleParent input#toggleValue').length)
返回 0。事实上, alert(jQuery('div#toggleParent h2').length)
返回 0,即使该元素上的单击事件刚刚触发!
我缺少什么?
Boiled down to the barest element, I just want to set a hidden field's value when I click an element on the page.
HTML:
<div id="toggleParent">
<input type="hidden" name="toggleValue" id="toggleValue" value="closed" />
<h2>Click Me</h2>
</div>
jQuery:
jQuery(document).ready(function() {
var toggle;
jQuery('div#toggleParent h2').click(function () {
if (toggle == '' || toggle == 'open') {
toggle = 'closed';
} else {
toggle = 'open';
}
jQuery('div#toggleParent input#toggleValue').val(toggle);
});
});
Obviously, it's not working. (Why would I be here otherwise?) The click event is working fine, as I can step through it in Firebug. But when it gets to setting the value, the code fails. What's more, trying alert(jQuery('div#toggleParent input#toggleValue').length)
returns 0. In fact, alert(jQuery('div#toggleParent h2').length)
returns 0 even though the click event on that exact element just fired!
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这个:
应该是:
或者甚至:
或者...
请记住,使用 ID 时,不需要任何其他选择器,因为 ID 是唯一的。这就足够了:
This:
Should be:
Or even:
Or...
Keep in mind that when using IDs, any other selector is unnecessary since IDs are unique. This is sufficient:
您的“toggle”值未定义,您仅在 document.ready 中定义它,但不为其分配任何值。要分配,请使用
Your 'toggle' value is undefined, you only define it in document.ready, but do not assign any value to it. To assign, use
我建议这个代码:
I propose this code:
试试这个代码:
Try this code: