2017-07-19 228 views
0

我有一張表列出一些評論。在評論旁邊有兩個鏈接,hideshow。所以我想要做的是當點擊右邊的鏈接來改變評論的狀態與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> 

如何定位點擊了哪個鏈接並執行ajax調用以切換評論狀態?

+0

嘗試也許'$(本).attr( '數據時間')' –

+0

只是一些額外的信息:警告沒有火起來,但是當我點擊鏈接之一,而不是它滾動頁面頂部 – Lykos

+1

嘗試添加e.preventDefault()到開始 –

回答

1

你可以改變你的JQuery觸發點擊a標籤。此外,您應該添加e.preventDefault();,因爲這是要點擊a標記,這將防止默認操作。

$('.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>

+0

我做了代碼更新。現在我總是隻有第一排的時間 – Lykos

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

爲什麼downvote?請給出意見。 –

+1

不是downvoter,但'publish-history-comment-link'被分配給錨,所以不需要'.find(a)' – Satpal

+0

我做了代碼更新。現在我總是隻有第一排的時間 – Lykos