0

我有一个<div id="comment_posting_holder">标签,其中包含一个包含两个元素的表单:一个 textarea 框和一个提交按钮。

如果我单击“其他”而不是提交按钮的某个位置,我希望 div 标签(包含 textarea 和提交按钮)消失。我对下面的代码有一个开始。所以在离开文本区域的焦点后,我可以让 div 标签消失。

问题是如果 div 消失了,提交按钮也会消失,这意味着我无法提交表单!我怎样才能解决这个问题?

有什么建议么?谢谢!

**Facebook 通过它的评论来做到这一点。如果您单击“发表您的评论...”字段,则会出现文本区域,然后它会在失去焦点时消失,除非您按下提交按钮。

$('textarea').blur(function() {
     $('#comment_posting_holder').hide();
});
4

3 回答 3

3

如果你想要一个像 facebook 这样的实现,你需要检查是否有人在文本框中写了一些东西。

你可以在这里看到我的答案

HTML

<div>
   <textarea class="comment_empty">Write a comment</textarea><br />
   <input type="submit" id="submit" value="Submit" style="display: none" />
</div>

jQuery

$(document).ready(function(){
    var submit = $("#submit");

    $("textarea").blur(function() {
        if ($(this).val() == "") {
            $(this).val("Write a comment")
                   .removeClass("comment_filled")
                   .addClass("comment_empty");
            submit.hide();
        }
    }).focus(function() {
        if ($(this).val() == "Write a comment") {
            $(this).val("")
                   .removeClass("comment_empty")
                   .addClass("comment_filled");
            submit.show();
        }
    });
});

一些 CSS

.comment_empty {
   color: gray;
   height: 30px;
}

.comment_filled {
   color: black;
   height: 100px;
}
于 2010-05-12T04:46:45.207 回答
3

我理解你想要什么:
如果用户点击任何地方,并且点击的元素不是提交按钮,那么隐藏 div。

执行此操作的代码:

$(document).ready(function() {
  $(document).click(function(event) {
    if (event.target.id == "idOfSubmitButton") {
      //user clicked the submit button (make sure to give it an ID)
      //if you wanted to be really hardcore, you could submit the form here via AJAX
    }
    else {
      //user clicked anywhere on the page but the submit button
      //here you'd want to check and make sure someone has actually typed
      //something in the textarea, otherwise this will happen for every
      //click on a hyperlink, button, image, et cetera on the page
      $('#comment_posting_holder').hide();
    }
  });
});
于 2010-05-12T04:49:01.813 回答
1

由于代码中的语法错误,Was 无法正常工作。除了缺少的单引号之外,您所拥有的看起来不错,只要它是在实际触发的事件中。试试这个:

$(document).ready(function(){
    $('textarea').blur(function() {
        $('#comment_posting_holder').hide();
    });
});
于 2010-05-12T03:50:40.630 回答