代码之家  ›  专栏  ›  技术社区  ›  Schoffelman

jquery复制文本并粘贴到文本区域

  •  1
  • Schoffelman  · 技术社区  · 16 年前

    我已经创建了一个javascript函数,它将获取一个隐藏的范围,复制该范围内的文本,并将其插入网站上的单个文本区域标记中。我用javascript编写了一个函数来实现这个目的(好吧,有点像,只需点击几下鼠标),但我知道有更好的方法——有什么想法吗?这种行为类似于twitter的转发,但使用博客上的文章部分代替。哦,我还在标题中调用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>
    
    3 回复  |  直到 15 年前
        1
  •  1
  •   Alex Plugaru    16 年前
    $("#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时绑定到$(“report-”+postid)按钮或链接。

        2
  •  2
  •   Paolo Bergantino    16 年前

    基于您问题中的评论,我假设您的HTML中有类似的内容:

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

    我还假设,因为您传递的是一个post id,所以每页可以有多个post 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中来进行快速而肮脏的修复。

        3
  •  0
  •   citadelgrad    15 年前

    当我点击链接时,我对Paolo的例子有异议,出现在cat-post-box中的文本是“对象对象”。一旦我在语句的末尾添加了“.text()”,我就开始工作了。

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

    谢谢你的例子,保罗!