【问题标题】:Is there any way to append text with jQuery only to the same div有没有办法将带有 jQ​​uery 的文本仅附加到同一个 div
【发布时间】:2015-07-15 02:41:04
【问题描述】:

我正在做一个评论系统。我有一个带有一些笑脸图像的 div。每次单击图像时,图像文本都会附加到文本区域。但问题是,每次我点击笑脸图像时,它都会将文本附加到页面上的所有文本区域,因为所有的 Teaxtarea 都具有相同的类。我也尝试为 textarea 提供一个 id,但它只会将文本附加到第一个 teatarea

这是我的 HTML 代码:

<a href="javascript:void(0)" onclick="appendpostid(' :3 ')">
    <img src="emotions/fb/colonthree.gif" class="smiley">
</a>

<textarea class="comment" name="comment" required></textarea>

还有 jQuery 脚本:

<script>
    function appendpostid( postid ) {
        $('.comment').val($('.comment').val() + postid);
    }
</script>  

【问题讨论】:

  • 你必须在 textarea 中添加一个 id,然后从那里看起来相当明显......

标签: jquery html


【解决方案1】:

试试这个

<a href="javascript:void(0)" onclick="appendpostid(e, this,' :3 ')">
    <img src="emotions/fb/colonthree.gif" class="smiley">
</a>

<textarea class="comment" name="comment" required></textarea>

和jquery

<script>
    function appendpostid(e, elem, postid ) {
        e.preventDefault();
        var textElem = $(elem).next('.comment');
        textElem.val(textElem.val() + postid);
    }
</script>  

【讨论】:

    【解决方案2】:

    听上去你想要多组这些按钮和文本区域。在这种情况下,一种选择是使用.next() 方法为按钮选择文本区域,该方法选择DOM 中的下一个元素。您可以使用 .comment 类作为选择器来定位它。

    在这个例子中,我还稍微修改了您的 HTML,将帖子 ID 作为数据属性放入,并应用了一个类,您可以使用该类来使用 jQuery 绑定点击事件:

    <a href="#" data-post-id=" :3 " class="appender">
        <img src="emotions/fb/colonthree.gif" class="smiley"/>
    </a>
    

    然后是你的 jQuery:

    $('.appender').click(function(e) {
        e.preventDefault();
        var postId = $(this).data('post-id');
        $(this).next('.comment').append(postId);
    });
    

    Here's an example 带有多组 this。

    【讨论】:

      猜你喜欢
      • 2013-06-01
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 2014-07-10
      相关资源
      最近更新 更多