【问题标题】:How to add <textarea> before button with jquery如何在带有 jquery 的按钮之前添加 <textarea>
【发布时间】:2015-12-08 16:16:45
【问题描述】:

我有一个简单的“新闻文章”列表,我希望可以发表评论。我创建了一个“添加评论”按钮。

我希望按钮在单击按钮之前立即创建一个带有&lt;textarea&gt;&lt;form&gt;,并在单击按钮之后立即创建一个“取消”按钮。 (我在提出这个问题时发现了这一点)

唯一剩下的是我希望“取消”按钮在单击时删除新创建的&lt;textarea&gt; 及其本身。并且为了获得额外的积分,如何防止“添加评论”按钮制作多个空白“文本区域”?

$(document).ready(function(){
	$(".AddComment").click(function () {
	    $("<form><textarea name='ResearchUpdate' placeholder='Enter your comment here' rows='3' cols='40' class='Commentary'></textarea> </form>").insertBefore(this);
	    $("<button class='CancelComment'>Cancel</button>").insertAfter(this);
	});
	
	$(".CancelComment").click(function (){
		$(this).prev(".Commentary").remove();
		$(this).remove();
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>News Entries</title>

</head>
<body>

<h2><a href="#">Killer Rabbit On The Loose</a></h2>
<p>Date: 01/23/2015</p>
<p>Author: Bobert</p>
<p>Subject: Animals</p>
<p>Most Recent Comment: None Yet.</p>
<button class="AddComment">Add Comment</button>

<h2><a href="#">Porsche Unveils Ultra Fast Minivan</a></h2>
<p>Date:02/14/2015</p>
<p>Author: Jimmy</p>
<p>Subject: Cars</p>
<p>Most Recent Comment:</p>
<p>This is genius on Porsche's behalf! I can drop off the kids at school, go grocery shopping and still have time to go racing with my buddies. All without worrying that my emissions aren't falsified and polluting the world.  --SemiProRacer997</p>
<button class="AddComment">Add Comment</button>


<h2> <a href="#">Apple Releases iPhone Inifity</a></h2>
<p>Date:03/11/2015</p>
<p>Author: Frank</p>
<p>Subject: Technology</p>
<p>Most Recent Comment:</p>

<button class="AddComment">Add Comment</button>


</body>
</html>

【问题讨论】:

    标签: javascript jquery forms textarea


    【解决方案1】:
    <script type="text/javascript">
        $('.AddComment').one('click',function(e){
            e.preventDefault();
            var bt=$(this);
            var el=$('<textarea name="comment" />');
            el.insertBefore(this);
            bt.text('Send comment').on('click',function(e){
                if (el.val().length==0){
                    alert("Please fill the comment before send.");
                    el.focus(); //Delete this row if you don't want user to focus on the textarea.
                    return false;
                }
                $.ajax({   
                    type: 'POST',
                    data : el,
                    cache: false,  
                    url: 'postUrl.php',
                    success: function(data){
                        bt.after($('<b>Comment sent</b>').hide().fadeIn());
                        bt.add(el).hide();
    
                    }   
                })
            })
        })
    </script>
    

    【讨论】:

    • 使用 one 创建文本区域(一次性),然后绑定提交事件。
    • 我正在尝试以您的建议为基础,因为最终我想通过 ajax 提交此信息。如何确保没有创建多个文本区域,最后如何在文本区域中有文本时运行 ajax?
    • 我在代码中使用了 ONE,以防止创建多个文本区域。 ajax 调用已经在代码中,只需将 'postUrl.php' 更改为您需要接收数据的 url。
    • 对很多 cmets 向导感到抱歉,我对堆栈溢出 cmets 区域的新行有一些问题。最后我编辑了答案,所以你可以看到防止任何空 cmets 的代码。 ;)
    【解决方案2】:

    显示和隐藏已经存在的项目比动态创建和插入它们更好。

    添加评论不超过一个文本区域的额外功劳:

    $(".AddComment").click(function () {
        $("<form><textarea name='ResearchUpdate' placeholder='Enter your comment here' rows='3' cols='40' class='Commentary'></textarea> </form>").insertBefore(this);
        $("<button class='CancelComment'>Cancel</button>").insertAfter(this);
        // Remove the click event and disable the button.
        $(this).off("click").prop("disabled", true);
    });
    

    我提出的解决方案:

    确保在每个帖子的评论框中都加载了 .comment-boxstyle="display: none;" 类,并使用以下事件处理程序。

    $(".AddComment").click(function () {
      $(this).prev(".comment-box").toggle();
    });
    

    此外,您可以让cancel 按钮拥有以下事件处理程序:

    $(".cancel").click(function () {
      $(this).closest(".AddComment").hide();
    });
    

    【讨论】:

      【解决方案3】:

      最好的解决方案是用一个 css 类将每个帖子项包装在一个容器 div 中,我们可以稍后将其用于 jQuery 选择。

      <div class="postItem">
        <h2><a href="#">Killer Rabbit On The Loose</a></h2>
        <p>Date: 01/23/2015</p>
        <p>Author: Bobert</p>    
        <button class="AddComment">Add Comment</button>
      </div>
      
      <div class="postItem">
        <h2><a href="#">Second post</a></h2>
        <p>Date: 01/23/2015</p>
        <p>Author: Shyju</p>    
        <button class="AddComment">Add Comment</button>
      </div>
      

      然后在你的取消按钮点击事件中,获取容器 div,找到表单和取消按钮并将其删除,

      $(document).on("click",".CancelComment",function (e){
      
          var _this = $(this);
          _this.closest(".postItem").find("form").remove();
          _this.remove();       
      
      });
      

      工作样本here

      您需要使用 jQuery on 方法来绑定取消按钮上的点击事件,因为它们是由您的代码动态创建并注入到 DOM 中的。

      【讨论】:

        【解决方案4】:

        我应该已经有了表单,但是将它隐藏起来,这样当您单击按钮时它就会出现。然后,您可以使用 $('#buttonId').prop('disabled', true); 禁用该按钮

        这将阻止任何进一步的点击,尽管这种点击无论如何都无关紧要,因为您只有一个要显示的表单,因此它不会再弹出。

        单击取消按钮应该会触发一个函数,该函数会删除相关文本区域的内容、隐藏表单/文本区域并重新启用评论按钮

        show_comment:

        function show_comment(){<br>
        &nbsp;&nbsp;&nbsp;&nbsp;$('#formId').show();<br>
        &nbsp;&nbsp;&nbsp;&nbsp;$('#cancelButton').show();<br>
        &nbsp;&nbsp;&nbsp;&nbsp;$('#commentButton').prop('disabled', true)<br>
        }
        

        删除评论:

        function remove_comment(){<br>
        &nbsp;&nbsp;&nbsp;&nbsp;$('#textareaId').html('');<br>
        &nbsp;&nbsp;&nbsp;&nbsp;$('#commentButton').prop('disabled', false);<br>
        &nbsp;&nbsp;&nbsp;&nbsp;$('#cancelButton').hide();
        
        }
        

        【讨论】:

          【解决方案5】:

          代码中的问题。

          1. 您正在为页面加载时不存在的取消按钮添加点击功能。添加取消按钮后,您必须添加点击
          2. 您在取消按钮上执行 prev(),这是错误的。取消按钮的上一个兄弟是添加评论按钮,而不是文本区域。

          请查看以下代码是否可以解决您的问题。 添加评论文本区域后,我还将禁用添加按钮,这样您就不会添加更多文本区域

          $(document).ready(function(){
          	$(".AddComment").click(function () {
                      var $addCommentBtn = $(this), 
                          $commentTextArea;
                      $addCommentBtn.prop( "disabled", true );
          	    $commentTextArea = $("<form><textarea name='ResearchUpdate' placeholder='Enter your comment here' rows='3' cols='40' class='Commentary'></textarea> </form>").insertBefore(this);
          	    $("<button class='CancelComment'>Cancel</button>").insertAfter(this).click(function (){
          		$commentTextArea.remove();
          		$(this).remove();
                          $addCommentBtn.prop( "disabled", false );
          	    });
          	});
          });
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
          <!DOCTYPE html>
          <html>
          <head>
          <title>News Entries</title>
          
          </head>
          <body>
          
          <h2><a href="#">Killer Rabbit On The Loose</a></h2>
          <p>Date: 01/23/2015</p>
          <p>Author: Bobert</p>
          <p>Subject: Animals</p>
          <p>Most Recent Comment: None Yet.</p>
          <button class="AddComment">Add Comment</button>
          
          <h2><a href="#">Porsche Unveils Ultra Fast Minivan</a></h2>
          <p>Date:02/14/2015</p>
          <p>Author: Jimmy</p>
          <p>Subject: Cars</p>
          <p>Most Recent Comment:</p>
          <p>This is genius on Porsche's behalf! I can drop off the kids at school, go grocery shopping and still have time to go racing with my buddies. All without worrying that my emissions aren't falsified and polluting the world.  --SemiProRacer997</p>
          <button class="AddComment">Add Comment</button>
          
          
          <h2> <a href="#">Apple Releases iPhone Inifity</a></h2>
          <p>Date:03/11/2015</p>
          <p>Author: Frank</p>
          <p>Subject: Technology</p>
          <p>Most Recent Comment:</p>
          
          <button class="AddComment">Add Comment</button>
          
          
          </body>
          </html>

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-09-12
            • 2016-07-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多