2016-12-06 65 views
1

我有textarea的表單,允許用戶添加回復jQuery的 - 如何將內容複製到文本區域

我想添加按鈕,每次回覆(類「quoteMsg」)。點擊它將複製回覆內容(有class =「replyMsg」)+作者姓名+日期(在SPAN標籤內)到textarea(name =「msgText」)+在內容前後添加「$」備註

下面是HTML例子:

<form method="post" action='index.php' id="submitReply"> 
    <p><textarea name="msgText"></textarea> <span></span></p> 
</form> 

<section class="replyBox"> 
     <article class="left"> 
      <header> 
       <h2>Re: Voucher Release Prblm - Comm</h2> 
       <span>By esther <strong>&raquo;</strong> 21-10-2014 12:06</span> 
       <a href="#" class='quoteMsg'>Quote</a> 
      </header> 

      <div class="replyMsg"> 
       If will happen again, I will open a new track<br /> 
      </div> 
     </article> 
</section> 

<section class="replyBox"> 
    <article class="left"> 
     <header> 
      <h2>Re: Voucher Release Prblm - Comm</h2> 
      <span>By esther <strong>&raquo;</strong> 23-07-2014 11:19</span> 
      <a href="#" class='quoteMsg'>Quote</a> 
     </header> 

     <div class="replyMsg"> 
      OK, thanks 
     </div> 
</section> 

我應該做這樣的事情:

<script>  
$('.quoteMsg').click(function() 
{ 
    var msgContent = parents("article").find(".replyMsg").val(); 
    //alert(msgContent); 

}) 
</script> 

? 如果是的話 - 我怎麼把裏面的textarea字段?

回答

2

您可以使用jQuery的closest()屬性來找到這樣的元素:

$(document).on('ready', function() { 
 
\t $('.quoteMsg').click(function() { 
 
\t \t var txt = $(this).closest('.replyBox').find('.replyMsg').text(); 
 
\t \t $("textarea[name='msgText']").val($.trim(txt)); 
 
\t }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form method="post" action='index.php' id="submitReply"> 
 
    <p><textarea class="msgText" name="msgText"></textarea> <span></span></p> 
 
</form> 
 

 
<section class="replyBox"> 
 
     <article class="left"> 
 
      <header> 
 
       <h2>Re: Voucher Release Prblm - Comm</h2> 
 
       <span>By esther <strong>&raquo;</strong> 21-10-2014 12:06</span> 
 
       <a href="#" class='quoteMsg'>Quote</a> 
 
      </header> 
 

 
      <div class="replyMsg"> 
 
       If will happen again, I will open a new track<br /> 
 
      </div> 
 
     </article> 
 
</section> 
 

 
<section class="replyBox"> 
 
    <article class="left"> 
 
     <header> 
 
      <h2>Re: Voucher Release Prblm - Comm</h2> 
 
      <span>By esther <strong>&raquo;</strong> 23-07-2014 11:19</span> 
 
      <a href="#" class='quoteMsg'>Quote</a> 
 
     </header> 
 

 
     <div class="replyMsg"> 
 
      OK, thanks 
 
     </div> 
 
    </article> 
 
</section>

希望這有助於!

+0

謝謝!你知道我需要改變什麼來點擊按鈕「報價」不會跳到我的頁面頂部? – roi

0

簡單的方式

$('.quoteMsg').click(function() 
{ 
    var msgContent = $(this).closest("article").find(".replyMsg").text(); 
    console.log(msgContent); 
}); 
相關問題