简体   繁体   中英

Click links to hide/show content

I'm having a table listing some comments. Next to the comment there are two links, the hide and show . So what I want to do is when clicking the right link to change the comment's status with ajax.

// inside a loop for showing all comments
<div class="pull-right" class="publish-history-comment">
    <a href="#" data-time="<?= $row->time; ?>" class="publish-history-comment-link" onclick="toggleHistoryNotes('publish');">Publish</a>
</div>
<div class="pull-right" class="hide-history-comment">
    <a href="#" data-time="<?= $row->time; ?>" class="hide-history-comment-link" onclick="toggleHistoryNotes('hide');">Hide</a>
</div>
<?= $row->comment; ?>

<script type="text/javascript">
    function toggleHistoryNotes(status) {
        var link = $('.' + status + '-history-comment-link');
        var time = link.attr('data-time');
        alert(time);
    }
</script>

How can I target which link was clicked and do the ajax call to toggle the comment status?

You can change your JQuery to trigged on click on a tag. Also, you should add e.preventDefault(); as this is gonna be click on the a tag, and this would prevent default action.

 $('.pull-right a').on('click', function(e) { e.preventDefault(); var time = $(this).data('time'); console.log($(this).text() + ' == ' + time); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="pull-right" class="publish-history-comment"> <a href="#" data-time="2133124356354" class="publish-history-comment-link">Publish</a> </div> <div class="pull-right" class="hide-history-comment"> <a href="#" data-time="2465433141212123" class="hide-history-comment-link">Hide</a> </div> 

<script type="text/javascript">
    $('a').on('click', function(e) {
      e.preventDefault();
      var time = $(this).data('time');
    });
</script>

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