显示更多/显示更少 JavaScript 无法正常工作

Show More / Show Less JavaScript not working properly

我试图在 select 一个 "show more" link 时显示一个 div 标签。到目前为止, div 在页面加载时出现,这是我不想要的。然后当我 select "Show" link 时, div 消失了。我需要相反的事情发生,然后当我再次 select link 时让 div 消失。

这是我的 HTML:

<div class="VideoText" align="left">
<a href=""><span> <strong> Credits </strong> </span></a> 
<br> Directed By: <a href="#"> Link One </a>
<br> Edited   By: <a href="#"> Link Two </a>
<br>

<a href="#" id="hideshow">Show</a>

<div id="message">
    Credit: <a href="#"> Link Three </a> <br>
    Credit: <a href="#"> Link Four </a>  <br>

</div>
</div>

这是我的 .js 文件:

$('#hideshow') .click(function() {
    $('#hideshow') .text('Hide');
    $('#message') .show();
    }, function() {
    $('#hideshow').text('Show');
    $('#message') .hide();

});

我觉得我只是把一些代码放在了错误的地方。

这是我试图让代码正常工作的页面: http://www.kingdombrand.com/Film/Alek/Films/TestFilm

我个人会用 CSS:

隐藏 #message 元素
#message {
    display: none;
}

使用上面的方法,元素将默认隐藏。所以,我猜你的代码现在可以工作了,但我会把它稍微改成这样:

$('#hideshow').click(function() {
    $('#message').toggle();

    if ($(this).text() == 'Show') {
        $(this).text("Hide");
    else
        $(this).text("Show");
    } 
});

您可以使用 class 隐藏 div,然后使用 jQuery 的 toggleClass 方法切换 class on/off .

所以在你的 CSS:

.is-hidden {
    display: none;
}

然后是你的 HTML:

<div id="message" class="is-hidden">
    Credit: <a href="#"> Link Three </a> <br>
    Credit: <a href="#"> Link Four </a>  <br>
</div>

然后是你的 jQuery:

$('#message').click(function () {
    $(this).toggleClass('is-hidden');
});

试试这个 JS:

$('#hideshow').click(function(event) {
   event.preventDefault()

   if($('#hideshow').text() == 'Show'){
      $('#hideshow').text('Hide');
      $('#message').show();
   }
   else{
      $('#hideshow').text('Show');
      $('#message').hide();
   }
});

还有这个css:

#message {
   display: none;
}