如何使用 jQuery 获取要切换的链接文本值?

问题描述 投票:0回答:1

我有一大块文本,其中一半文本被隐藏。我使用 Bootstrap 5x 切换来显示和隐藏文本块。这很好用。

但是,当切换发生时,我也尝试将按钮文本从 显示更多更改为 显示更少。我有一些 jQuery 应该可以工作,但事实并非如此。文本不会从“显示更多”更改为“显示更少”。

这里是切换代码:

<div class="collapse more-collapse" id="moreContent{sub_topic:entry_id}">
    {sub_topic:more_text}
</div>
<p><a class="red more-toggler custom-toggler me-4" data-bs-toggle="collapse" data-bs-target="#moreContent{sub_topic:entry_id}" aria-controls="moreContent" aria-expanded="false" aria-label="Toggle more-content">
Show <span>more</span><span class="hidden">less</span> &#8250;</a></p>

这是 jQuery(运行 jQuery 3.7.1):

$(document).ready(function() {
    $('.hidden').removeClass('hidden').hide();
    $('.toggle-text').click(function() {
    $(this).find('span').each(function() { $(this).toggle(); });
    });
});
jquery twitter-bootstrap toggle
1个回答
0
投票

您的选择器可能是错误的,我在您的标记中没有看到任何

.toggle-text

下面我使用锚标记中的
.custom-toggler
来设置单击事件处理程序。

$(document).ready(function() {
    $('.hidden').removeClass('hidden').hide();
    $('.custom-toggler').click(function() {
        $(this).find('span').toggle(); 
        $(this).parent().prev().toggleClass('collapse');
    });
});
.collapse{
    height: 1em;
    overflow: hidden;
}
[id^=moreContent]{
   white-space: pre;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="collapse more-collapse" id="moreContent{sub_topic:entry_id}">What do they got? A lot of sand
We got a hot crustacean band
Each little clam here
Know how to jam here
Under the sea
Each little slug here
Cuttin' a rug here
Under the sea
Each little snail here
Know how to wail here
That's why it's hotter
Under the water
Ya we in luck here
Down in the muck here
Under the sea
</div>
<p><a class="red more-toggler custom-toggler me-4" data-bs-toggle="collapse" data-bs-target="#moreContent{sub_topic:entry_id}" aria-controls="moreContent" aria-expanded="false" aria-label="Toggle more-content">
Show <span>more</span><span class="hidden">less</span> &#8250;</a></p>

© www.soinside.com 2019 - 2024. All rights reserved.