简体   繁体   English

关于选择表格儿童jquery的问题

[英]Question about selecting form children jquery

Again I'm asking question about comment form, I'm making an image website and every image has its own comment form, so when I submit form I do like this : 我再次询问有关评论表单的问题,我正在制作一个图片网站,每个图片都有自己的评论表单,所以当我提交表单时,我喜欢这样:

$('#comment_form').live('submit', function() {
 ...

So in order to select only this form textearea value I tried using this but I get undefined error here is how I tried : 所以为了只选择这种形式的textearea值我尝试使用这个,但我得到未定义的错误这里是我尝试的方式:

$('#comment_form').live('submit', function() {
 image_comment_text=$(this).closest("#comment_text").val(); //textarea id is comment_text

I tried to used find(), its working but when I submit comments for few images I get comments 2 or 3 times as I should, because find finds all occurrences of textarea with comment_text id .. how can I do this ? 我试图使用find(),它的工作,但当我提交几个图像的评论时,我得到2或3次评论,因为我发现所有出现的textarea与comment_text id ..我怎么能这样做?

@molf , here is HTML generated by javascript: @molf,这里是javascript生成的HTML:

var xHTML = "<div class=\"addComment\">";
   xHTML += "<form action=\"<?=base_url()?>images/post_comment/" + post + "\" method=\"post\" class=\"comment_form\" name=\"comment_form\">";
   xHTML += "<input type=\"hidden\" class=\"comment_post_id\" name=\"comment_post_id\" value=\"" +post + "\"/>"; 
   xHTML += "<textarea class=\"comment\" name=\"comment_text\" rows=\"8\" cols=\"40\"></textarea>";
      xHTML += "<input type=\"submit\" name=\"submit\" class=\"post_image_comment\" value=\"Comment\"><span> Don't make it too big!</span>";
   xHTML += "</form></div>";

EDIT 编辑

When I print to console log the value of textarea I get only one result as I should, now when I try to append the ul comments I get 2 of the same values .. here how it goes .. 当我打印到控制台记录textarea的值时,我只得到一个结果,现在当我尝试追加ul注释时,我得到2个相同的值..这里是怎么回事..

<ul class="comments"></ul> 

below is the comment form which is not in the document at all, when certain anchor is clicked the form pops out below .comments , when form submits I want to append the comments to add the new comment to list items of existing unordered list comments , here is the whole code : 下面是评论表单,根本不在文档中,当单击某个锚时,表单弹出以下.comments ,当表单提交时我想附加注释以添加新注释以列出现有无序列表注释的列表项,这是整个代码:

$('form[name^="comment_form"]').live('submit', function(event) {
  r= $(this).find('> .comment').val();

                $('<div class="overlay"></div>')
    .appendTo('.addComment')
             .fadeIn(200, function() {
          $('.comments')
             .append('<li id="new_append">' + r + '</li>')
              .children(':last')
           .height($('.comments li:last').height())
           .hide()
           .slideDown(800, function() { 
             var bodyHeight = $('html').height();
            $('.addComment').fadeOut(500, function() {
              $('html').height(bodyHeight);
           $('h2#leaveAComment').fadeOut(200, function(){$(this).text('Thank you for your comment!').fadeIn(200)});
          });
         });  
        $('html, body').scrollTo( $('#new_append'), 800 );
        });
    event.preventDefault();
            }); 

EDIT II @patrick 编辑II @patrick

The javascript which loads the comment form is above .. here is HTML : 加载评论表单的javascript在上面..这里是HTML:

-------------BEGIN FOR EACH-------------- -------------每个开始--------------

<div id="image-12" class="image_content">
<img src="..." />
 <ul class="comments hidden"> //This is where the comments are appended to <li></li>

 </ul>

<div style="float: left; display: block; width: 100%;">
<a id="image_comment-12" class="image_comment" onclick="showComments('12');" href="javascript:;">Add Comment</a>
</div>

  <div id="addComment-12">//this is where the comment form loads

  </div>

</div>

----------END--- FOR EACH--------- image ... ----------结束---每个---------图片......

First of all, change your selector for your form. 首先,更改表单的选择器。 I think you can select form by name using the id selector, but you're not supposed to duplicate ids on a page, so jQuery live is probably only watching the first form. 我认为您可以使用id选择器按名称选择表单,但是您不应该在页面上复制id,因此jQuery live可能只是在观看第一个表单。 This is just a guess, though. 但这只是猜测。

Also, it doesn't matter what class/id you use for your textarea. 此外,您使用textarea的类/ ID无关紧要。 If you're only going to have one textarea per form, you can use the :text selector. 如果每个表单只有一个textarea,则可以使用:text选择器。 When finding children, I like to use the children selector. 在寻找孩子时,我喜欢使用儿童选择器。

$('form[name="comment_form"]').live('submit', function() {
  image_comment_text = $(this).find('> :text').val();
});

If you're using name instead of id because you're going to have multiple forms, I would suggest changing the name to comment_form_'image_id', then your selector would be: $('form[name^="comment_form"]') 如果您使用的是name而不是id,因为您将有多个表单,我建议将名称更改为comment_form_'image_id',然后您的选择器将为: $('form[name^="comment_form"]')
Notice the ^ which requires the name to start with 'comment_form'. 注意^需要名称以'comment_form'开头。 That way, you can have unique form names (comment_form_234, comment_form_235) and still have the desired effect. 这样,您可以拥有唯一的表单名称(comment_form_234,comment_form_235)并仍然具有所需的效果。

Edit: 编辑:

I looked at your code update, and it looks to me like you're ignoring the context of the current form in your function. 我看了你的代码更新,它看起来像你忽略了函数中当前表单的上下文。 For instance, when you use the selector $('.comments').append(... you're appending to all elements on your page which match that selector. In order to retrieve the proper elements, you'll have to always use your selector as $(this).find(' > .comments').append(... which will work within the context of the submitted form. 例如,当你使用选择器$('.comments').append(...你附加到页面上与该选择器匹配的所有元素。为了检索正确的元素,你必须总是使用您的选择器作为$(this).find(' > .comments').append(...将在提交的表单的上下文中工作。

I took a few minutes to edit your code, I haven't run it or anything, but it should be close to what you're trying to do. 我花了几分钟编辑你的代码,我没有运行它或任何东西,但它应该接近你想要做的。 I hope it at least gets you started in the right direction: 我希望它至少让你开始朝着正确的方向前进:

$('form[name^="comment_form"]').live('submit', function (event) {
    r = $(this).find('> .comment').val();
    /* get addComment-classed element */
    var addComment = $(this).find(' > .addComment:first');

    /* get comments-classed element */
    var comments = $(this).find(' > .comments:first');

    $('<div class="overlay"></div>').appendTo(addComment).fadeIn(200, function () {
        /* note comments element, not selector */
        $(comments).append('<li id="new_append">' + r + '</li>').children(':last').height(
        /* again, element */
        $(comments).find(' > li:last').height()).hide().slideDown(800, function () {
            var bodyHeight = $('html').height();

            /* again, element */
            $(addComment).fadeOut(500, function () {
                $('html').height(bodyHeight);
                $('h2#leaveAComment').fadeOut(200, function () {
                    $(this).text('Thank you for your comment!').fadeIn(200)
                });
            });
        });
        $('html, body').scrollTo($('#new_append'), 800);
    });
    event.preventDefault();
});

I added comments in the code, but notice that the addComments and comments selectors are 'cached'. 我在代码中添加了注释,但请注意addComments和注释选择器是“缓存”的。 If you're going to be accessing these elements multiple times, storing them in a variable before using them will cut back on DOM traversals. 如果您要多次访问这些元素,在使用它们之前将它们存储在变量中将减少DOM遍历。 This should really solve your comments being added to multiple elements on your page. 这应该可以解决您的评论被添加到页面上的多个元素的问题。

First, the find() method was the correct way to go if used within the proper context. 首先,如果在适当的上下文中使用,find()方法是正确的方法。

Second, it sounds like you are re-using IDs. 其次,听起来你正在重新使用ID。 This is not allowed. 这是不允许的。 An ID can be used only once on a page. ID只能在页面上使用一次。

The closest() function searches 'up' from (and including) the DOM element. nearest()函数从(或包括)DOM元素中搜索“up”。 The find() function searches the content of the element. find()函数搜索元素的内容。

EDIT: 编辑:

I assume the form is being submitted when the user clicks the submit button. 我假设用户单击提交按钮时正在提交表单。 I also assume that there's more to your submit() handler than is shown. 我还假设你的submit()处理程序比显示的更多。 Is that correct? 那是对的吗?

Sometimes you need to add $(this).preventDefault(); 有时您需要添加$(this).preventDefault(); in order to keep the form from being submitted in your code, as well as by the default behavior of the 'submit' button. 为了防止在您的代码中提交表单,以及“提交”按钮的默认行为。

The following does the same thing (essentially) as find(). 以下(基本上)与find()完成相同的事情。 It will find the item with the .comment_text class within the form being submitted. 它将在提交的表单中找到带有.comment_text类的项目。 So it should only grab the value of one item: 所以它应该只抓取一个项目的值:

image_comment_text=$(".comment_text", this).val();

How many comment_form s do you have on a each page? 你在每个页面上有多少个comment_form For correct HTML you should only have one id='comment_text' and one id='comment_form' per page. 对于正确的HTML,每页只应有一个id ='comment_text'和一个id ='comment_form'。

Consider changing your ids to class='comment_text' and finding with .comment_text rather than #comment_text 考虑将您的ID更改为class ='comment_text'并使用.comment_text而不是#comment_text进行查找


I think from your latest comments the issue may be the way you are dynamically adding your form/comments textbox to the page. 我认为,根据您的最新评论,问题可能是您将表单/评论文本框动态添加到页面的方式。

Once you've entered comments and submitted them do you then remove the form you've dynamically added? 输入评论并提交后,您是否删除了动态添加的表单? I would recommend this as if not I think your DOM structure is getting confused causing the problems you are experiencing. 我会推荐这个,好像不是我认为你的DOM结构变得混乱导致你遇到的问题。

You are getting duplicate comments because you aren't removing the previous add comment form. 您将收到重复的评论,因为您没有删除以前的添加评论表单。 Try adding this to the end of your .slideDown callback function: 尝试将此添加到.slideDown回调函数的末尾:

$(this).remove();

Here is the full submit function, I made a few changes/additions: 这是完整的提交功能,我做了一些更改/添加:

  • I removed the > from the find('.comment') as it isn't necessary 我从find('.comment')删除了> ,因为没有必要
  • Changed the new append to a class, then removed it after you scroll to it. 将新附加更改为类,然后在滚动到它后将其删除。
  • Removed the form when complete 完成后删除表单
  • Changed the event.preventDefault(); 更改了event.preventDefault(); to return false; return false; ... this is more of a personal preference than anything. ......这比个人更喜欢个人偏好。

I hope this helps :) 我希望这有帮助 :)

 $('form[name^="comment_form"]').live('submit', function(event) {
  r = $(this).find('.comment').val();
  $('<div class="overlay"></div>')
   .appendTo('.addComment')
   .fadeIn(200, function() {
    $('.comments')
     .append('<li class="new_append">' + r + '</li>')
     .children(':last')
     .height($('.comments li:last').height())
     .hide()
     .slideDown(800, function() {
      var bodyHeight = $('html').height();
      $('.addComment').fadeOut(500, function() {
       $('html').height(bodyHeight);
       $('h2#leaveAComment').fadeOut(200, function(){$(this).text('Thank you for your comment!').fadeIn(200)});
       $(this).remove();
      });
     });
     $('html, body').scrollTo( $('.new_append:last'), 800 );
     $('.new_append').removeClass('new_append');
   });
  return false;
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM