繁体   English   中英

jQuery复制文本并粘贴到textarea中

[英]JQuery Copy text & paste into textarea

我创建了一个javascript函数,该函数将使用隐藏的跨度,复制该跨度内的文本,并将其插入网站上的单个textarea标签中。 我已经用JavaScript编写了一个可以做到这一点的函数(好吧,只需单击几下),但是我知道有更好的方法-有什么想法吗? 行为类似于Twitter的Retweet,但使用博客上帖子的各个部分。 哦,我还在标题中调出了jquery。

<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>

根据您问题中的评论,我假设您的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中来进行快速而肮脏的修复。

$("#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.
});

并将所有内容包装在$(document).ready(function(){/ 在此处插入代码 /})中,以便在加载DOM时将其绑定到$(“#repost-” + postID)按钮或链接。

当我单击链接时,出现在#cat_post_box中的文本为“ object Object”时,Paolo的示例出现了问题。 在该语句的末尾添加“ .text()”后,我就可以工作了。

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

谢谢你的例子保罗!

暂无
暂无

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

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