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开发者_如何学JAVA 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');
}
});
If you're using a newer version of jQuery (1.3+) there's no @
on attribute selectors anymore, it just looks like this:
$("form[id^='sub_comment_form']").hide();
//and..
$("a[id^='sub_add_comment']").click(function() {
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:
$(function() {
$("form[id^='sub_comment_form']").hide();
$("a[id^='sub_add_comment']").click(function() { ... });
});
Alternatively, instead of these ID starts-with selectors you could use a class, for instance:
<a href="#" class="addComment">Add comment</a>
And bind it like this:
$("a.addComment").click(function() { ... });
Line 1 is missing the closing ']' so it should be...
$("form[@id^='sub_comment_form']").hide();
It is also a good practice to prefix variables containing jQuery objects with a $.
var $sibform = $(this).next("form");
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.
精彩评论