jQuery 选择器不起作用或无法绑定事件
我在一个页面上有几个动态创建的链接和表单,分别以 ID sub_comment_form_[id]
和 sub_add_comment_[id]
命名。我正在尝试:
- 页面加载时隐藏所有表单
- 将单击事件绑定到表单正上方的链接以隐藏/显示表单。
我不确定我的选择器是否有问题,或者 jQuery 是否根本不允许同时绑定多个对象。这是我的代码:
HTML
<a href="#" id="sub_add_comment_to_answer_[id]">Add comment</a>
<form id="sub_comment_form_to_answer_[id]"...
jQuery
$("form[ @id^='sub_comment_form' ]").hide();
$("a[ @id^='sub_add_comment' ]").click(function() {
var sibform = $(this).next("form");
if (sibform.is(':hidden')) {
$(this).text('Cancel');
sibform.slideDown('fast');
} else {
$(this).text('Add comment');
sibform.slideUp('fast');
}
});
I have several dynamically created links and forms on one page named with IDs sub_comment_form_[id]
and sub_add_comment_[id]
, respectively. I'm trying to:
- Hide all forms when the page loads
- Bind a click event to the link directly above the form to hide/show the form.
I'm not sure if there is a problem with my selectors, or if jQuery simply does not allow binding on multiple objects at once. Here is my code:
HTML
<a href="#" id="sub_add_comment_to_answer_[id]">Add comment</a>
<form id="sub_comment_form_to_answer_[id]"...
jQuery
$("form[ @id^='sub_comment_form' ]").hide();
$("a[ @id^='sub_add_comment' ]").click(function() {
var sibform = $(this).next("form");
if (sibform.is(':hidden')) {
$(this).text('Cancel');
sibform.slideDown('fast');
} else {
$(this).text('Add comment');
sibform.slideUp('fast');
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用的是较新版本的 jQuery (1.3+),则属性选择器上不再有
@
,它看起来像这样:第一个也缺少右大括号,因此请务必修复也是如此 :)
另外,请确保这两个都包装在
document.ready
处理程序中,以便它们在 DOM 准备好后执行,如下所示:或者,您可以代替这些 ID 开头的选择器例如,使用一个类:
并像这样绑定它:
If you're using a newer version of jQuery (1.3+) there's no
@
on attribute selectors anymore, it just looks like this:This first one was also missing a closing brace, so be sure to fix that too :)
Also, be sure both of these are wrapped in a
document.ready
handler so they execute after the DOM is ready, like this:Alternatively, instead of these ID starts-with selectors you could use a class, for instance:
And bind it like this:
第 1 行缺少结束符“]”,所以应该是......
Line 1 is missing the closing ']' so it should be...
在包含 jQuery 对象的变量前添加 $ 也是一个好习惯。
这样你就总能知道你什么时候在处理 jQuery 对象,什么时候没有。从而阻止您在其本身绑定 jQuery 对象。
It is also a good practice to prefix variables containing jQuery objects with a $.
This way you always know when you're dealing with a jQuery object and not. And thereby keeps you from binding a jQuery object in itself.