如何在forEach循环中隐藏/显示更多文本

时间:2017-06-23 11:15:48

标签: php jquery

我的代码是:

<?php 
$msgArray = [
0=>'HTTP means HyperText Transfer Protocol.',
1=>'HTTPS,Hyper Text Transfer Protocol Secure is the secure version of HTTP.'
];
foreach ($msgArray as $key => $msg) :
$small = substr($msg, 0, 5);?>
<span class="lessText"><?= $small ?></span>     
<span class="fullText" style="display: none"><?= $msg ?></span> 

<sub class="viewMore" style="color:#3399ff;padding-left2%;cursor: pointer;">view more >></sub>
<sub class="viewLess" style="color:#3399ff;padding-left2%;cursor: pointer;display: none"><< view less</sub>
<?php endforeach; ?>   

<script type="text/javascript">
$(".viewMore").click(function(){
$(".viewMore").hide();
$(".lessText").hide();
$(".fullText").show();
$(".viewLess").show();
});

$(".viewLess").click(function(){
$(".viewLess").hide();
$(".fullText").hide();
$(".lessText").show();
$(".viewMore").show();
});
</script>

在这里,我试图在其前五个字符中显示一个长字符串,点击查看更多后,它将显示整个字符串。 如果只有一个,这个工作正常。在 forEach 循环中,它无法正常工作。请解决这个问题。

2 个答案:

答案 0 :(得分:3)

将HTML片段包装在容器中。

<div class="container">
    <span class="lessText"><?= $small ?></span>     
    <span class="fullText" style="display: none"><?= $msg ?></span> 

    <sub class="viewMore" style="color:#3399ff;padding-left2%;cursor: pointer;">view more >></sub>
    <sub class="viewLess" style="color:#3399ff;padding-left2%;cursor: pointer;display: none"><< view less</sub>
</div>

然后修改脚本以使用DOM遍历方法来定位所需的元素。使用.closest()遍历公共父级,即container,然后将其用作context或使用.find()

$(".viewMore").click(function () {
    var container = $(this).closest('.container')   
    $(".viewMore, .lessText", container).hide(); //container.find('.viewMore, .lessText').hide()
    $(".fullText, .viewLess", container).show();
});

$(".viewLess").click(function () {
    var container = $(this).closest('.container')   
    $(".viewLess, .fullText", container).hide();
    $(".lessText, .viewMore", container).show();
});

答案 1 :(得分:-1)

将其写入此结构:

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = model_view_playground
TEMPLATE = app

DEFINES += QT_DEPRECATED_WARNINGS

QMAKE_CXXFLAGS += -std=c++0x

SOURCES += main.cpp\
        mainwindow.cpp \
    testitemlistmodel.cpp

HEADERS  += mainwindow.h \
    testclass.h \
    testitemlistmodel.h

FORMS    += mainwindow.ui

DISTFILES +=

<强> JS

<?php foreach(): ?>
<div class="holder">
 <div class="lessText"></div>
 <div class="fullText"></div>

 <div class="viewMore"></div>
 <div class="viewLess"></div>
</div>
<?php endforeach; ?>