简体   繁体   中英

When a link is clicked, grab the contents of another class

I am trying to take the Wordpress "reply" button for comments and making it grab the username of the comment you are replying to and post it into the comment textarea box like @USERNAME

Below is the output from my Wordpress comment. On line 6 there is a link that has a Class name url and the links text is jasondavis

Down farther down on line 15 there is the Reply link, it has a class of comment-reply-link

When a user clicks on that reply link, I am trying to get the Username in this case jasondavis so I can later insert it into the textarea box.

I think this can be done with jQuery, assume there are multiple of these comments on the page so when the Reply link is clicked, it has to be smart enough to get the text from .url but only from the .url that directly precedes the reply button for that particular comment that the reply button/link was clicked from.

If you have any tips or can help I would appreciate it

<li class="comment byuser comment-author-jasondavis bypostauthor even depth-2" id="comment-6">
    <div class="c-grav"><img alt="" src="http://1.gravatar.com/" class="avatar avatar-60 photo" height="60" width="60"></div>
    <div class="c-arrow"></div>
    <div class="c-body">
        <div class="c-head">
            <a href="http://www.codedevelopr.com/" rel="external nofollow" class="url">jasondavis</a>
            <span class="c-date">December 30, 2011 8:00pm</span>
        </div>
        <p>Comment body text is here......</p>

        <span class="edit-comment">
            <a class="comment-edit-link" href="" title="Edit comment">Edit</a>
            <a href="">Delete</a>
            <a href="">Spam</a>
            <a class="comment-reply-link" href="/codedevelopr/php-database-class/?replytocom=6#respond" onclick="return addComment.moveForm(&quot;comment-6&quot;, &quot;6&quot;, &quot;respond&quot;, &quot;5&quot;)">Reply</a>
        </span>
    </div><!--end c-body-->
</li>

Assuming your comment ul has an ID of comments :

$("#comments").on('click', '.comment-reply-link', function(e) {
    var name = $(this).parents('.comment').first().find('.url').text();
    alert('replying to ' + name);
    e.preventDefault();
});

Try it on JSFiddle.

Try this also on JSFiddle:

$(".comment-reply-link").click( function() { 
    username = $(this).parent().parent().children(".c-head").children(".url").html();   
    alert( username );
    return false; // to prevent further link processing by the browser.
});

To get value of the username, you have to walk through the tag nodes.

另一个替代方法与.parents有点不同:

var name = $(this).closest('.comment').find('.url').text();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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