JQuery复制文本并粘贴到textarea中

问题描述:

我创建了一个javascript函数,它将采用隐藏跨度,将该跨度内的文本复制并将其插入到网站上的单个textarea标记中。我已经写了一个JavaScript函数来做到这一点(好吧,只是点击几下),但我知道有一个更好的方法 - 任何想法?该行为类似于Twitter的Retweet,但是在博客中使用部分帖子。哦,我也在头上打电话给jquery。JQuery复制文本并粘贴到textarea中

<script type="text/javascript"> 
function repost_submit(postID) {  
    $("#repost-" + postID).click(function(){ 
     $("#cat_post_box").empty(); 
     var str = $("span#repost_msg-" + postID).text(); 
     $("#cat_post_box").text(str); 
    }); 
} 
</script> 
+0

哦,还有,postID会通过标记中的onclick传递 – Schoffelman 2009-07-01 21:43:02

$("#repost-" + postID).click(function(){ 
    $("#cat_post_box").val(''); // Instead of empty() - because empty remove all children from a element. 
    $("#cat_post_box").text($("#repost_msg-" + postID).text());//span isn't required because you have and id. so the selector is as efficient as it can be. 
}); 

,敷在$(文件)的一切。就绪(函数(){/ 这里插入代码 /}),因此它会绑定到$( “#repost-” +帖子ID)按钮或者在DOM加载时链接。

基于对你的问题的评论,我假设你有这样的事情在你的HTML:

<a href="#" onclick="repost_submit(5);">copy post</a> 

而且我还假设,因为你正在传递一个帖子ID可以有每页超过一页。

jQuery的美丽之处在于,您可以在不使用内联JavaScript事件的情况下为元素集做很酷的事情。这些现在被认为是不好的做法,因为最好是将Javascript与演示代码分开。

正确的方法,那么,将是做这样的事情:

<a href="#" id='copy-5' class='copy_link'>copy post</a> 

然后你就可以有更多的是类似于:

<a href="#" id='copy-5' class='copy_link'>copy post</a> 
<a href="#" id='copy-6' class='copy_link'>copy post</a> 
<a href="#" id='copy-7' class='copy_link'>copy post</a> 

最后,您可以编写代码jQuery做这样的事情:

$(function() { // wait for the DOM to be ready 
    $('a.copy_link').click(function() { // whenever a copy link is clicked... 
     var id = this.id.split('-').pop(); // get the id of the post 
     var str = $('#repost_msg-' + id); // span not required, since it is an ID lookup 
     $('#cat_post_box').val(str); // empty not required, and val() is the proper way to change the value of an input element (even textareas) 
     return false; 
    }); 
}); 

这是最好的方式来做到这一点,即使只有一个职位在这一页。代码的部分问题在于,第一次单击它时会绑定该函数,而在随后的单击操作中,它最终会被调用。你可以通过改变它来做一个快速而肮脏的修复,只需要在document.ready中。

当我点击链接时,出现在#cat_post_box中的文本是“对象对象”,Paolo的示例出现问题。一旦我将“.text()”添加到该声明的结尾,我就工作了。

var str = $('#repost_msg-' + id).text(); 

感谢你的例子保罗!