首页 > 解决方案 > 使用 jquery 选择跨度文本

问题描述

我有这个 html 代码,我想在点击回复时获取跨度文本,但是我的页面中有多个此代码,并且仅选择第一项,这是我的代码

<div class="display-comment" style="margin-right: 10px">
    <div class="userProfileImageForComment">
        <img src="{{asset('profile-media/'.$comment->user->profileimg)}}" alt="">
    </div>
    <span id="userName">{{ $comment->user->username }}</span>
    <p>{{ $comment->comment }}</p>
    <div class="comentActionAndDate">
        <span>
            {{ jdate($comment->created_at)->ago() }}
        </span>
        <a id="reply">
            reply
        </a>
    </div>

和脚本是

<script>
    $('#reply').click(function(){
        var username = "@" + $('#userName').text() + " ";
        $('#comment').val('');
        $('#comment').val(username);

        $('#comment').after( "<input type=\"hidden\" name=\"comment_id\" value=\"{{ $comment->id }}\" />" )

    });
</script>

标签: htmljquery

解决方案


var spanText = $(".comentActionAndDate span").html();

我假设这是一个评论线程,在这种情况下,您应该使用相对查找来定位文本。

$('#reply').click(function(){
    var spanText = $(this).find(".comentActionAndDate").children("span").html();
    // Other stuff you might want to do
});

如果不止一次生成该回复按钮,您也不应该为该回复按钮使用 ID。您还应该使用<button><a>标签,因为a标签用于链接。

最正确的方法是使用onclick回复按钮的功能:

<button onclick="getSpan(this);">reply</button>

JS:

function getSpan(ele) {
    var spanText = $(ele).find(".comentActionAndDate").children("span").html();
    // Other stuff you might want to do
}

推荐阅读