在表格单元格中显示更多/更少按钮(展开文本)

时间:2014-04-03 21:14:17

标签: javascript php jquery html-table

我有一个使用PHP填充的html表:

<table class="flat-table flat-table-1" width="100%">

<tr style="background-color:#FFF;">
    <td class="table-head">Name</td>
    <td class="table-head">Review</td>
    <td class="table-head">Rating</td>
</tr>

<?php
//run a query to find all the fields in the review table that belong to the specific hall, using the id in the url ($current_id)
if ($r = $db->prepare("SELECT * FROM reviews WHERE hall_id = :current_id")) {
    //bind the parameters used in the above query using the 'current_id' variable
    $r->bindParam(':current_id', $current_id);
    //Execute the prepared query
    $r->execute(); 

    //search review table for all fields and save them in $review
    $reviewtemp = $r->fetchAll();
    foreach( $reviewtemp as $review) {

    //loop and output the reviews
?>

<tr>
<td><? echo $review['name'];?></td>
<td><? echo $review['review']; ?></td>
<td><? echo $review['overall']; }}?></td>
</tr>
</table>

- <td><? echo $review['review']; ?></td>' - 包含需要使用show more / less按钮缩短的长篇文本,如果文本超过400个字符。

我尝试过使用我在互联网上找到的代码,但没有运气。我希望也许有人在这里可以指出我正确的方向?我很乐意使用任何解决方案。

以下代码是我需要使用的东西,但我不确定如何在代码中实现它:http://jsfiddle.net/Wpn94/326/

( - 之前我曾问过类似的问题,但没有回复。我现在已经改变了问题并再次发布了 - )

2 个答案:

答案 0 :(得分:1)

在以下代码中,我更新了HTML以包含多个审阅和使用表。 http://jsfiddle.net/3VTb7/

对javascript起作用的结构是这样的:

<table>
<tr><td>Name</td></tr>
<tr><td><div class="content hidecontent">insanely long review here</div><div class="show-more"><a href="#">Show More</a></div><td></tr>
</table>

注意:您必须拥有hidecontent类。 show more div应该直接在你要隐藏的内容之后,并包含show-more类。

不看你试图混在一起的代码,我无法确定还有什么可能是错的。

答案 1 :(得分:0)

这可能是一个错误:<td><? echo $review['overall']; }}?></td> 由于您要循环表格行,}应该在</tr>

之后
<tr>
<td><? echo $review['name'];?></td>
<td><? echo $review['review']; ?></td>
<td><? echo $review['overall']; ?></td>
</tr>
<?php }} ?>

回答问题,可能是:

首先,如果您使用了review_id,则在$id = 0;之前添加if ($r = $db->prepare("...

将评论分成两部分..

<td><?php
    $review = $review['review'];
    $short_length = 200;
    $short = substr($review, 0, $short_length);
    $long = substr($review, $short_length);
    $id++;
    echo $short . '<span class="content hidecontent" id="review'.$id.'">'.$long.'</span>
            <a href="javascript:" class="showmoreless" data-id=".$id.'">Show More</a>';
?></td>

然后使用jQuery切换

$("#hidecontent").click(function(){
    var reviewid = "#review"+$(this).data("id");
    $(reviewid).slideToggle(500, function(){
        var moreless = $(reviewid).is(":visible") ? 'Less' : 'More';
        $(this).html("Show "+moreless)
    });
});