0

Example fiddle - http://jsfiddle.net/S6CwT/

CSS

#service_container {
    display: none;
}

HTML

<a href="/services/update/8" id="view_service">View Service Record</a>

<div id="service_container">
    Test
</div>

jQuery

jQuery.noConflict();

jQuery(function() {

    // toggle visibility of service section
    jQuery('#view_service').click(function() {
        jQuery('#service_container').slideToggle('slow');
        // toggle text
        if (jQuery('#service_container').is(':visible')) {
            jQuery('#view_service').text('Hide Service Record');
        } else {
            jQuery('#view_service').text('View Service Record');
        }
        return false
    });

});

The bug is when clicking the link for the first time, the link text will change correctly to say Hide Service Record but on subsequent clicks the text will not change to Show Service Record when the div is hidden and back to Hide Service Record when the container is visible again.

Must be something silly I'm not spotting but can't see what I've done wrong.

I tried it the opposite way using is(:hidden) but that behaves the same way.

4

5 回答 5

2

尝试这个

jQuery(function() {

     jQuery("#service_container").hide();
     // toggle visibility of service section
     jQuery('#view_service').click(function()
     {
         // toggle text
         if (jQuery('#service_container').is(':visible'))
         {
             jQuery('#view_service').text('View Service Record');
         } 
         else 
         {
             jQuery('#view_service').text('Hide Service Record');
         }
         jQuery('#service_container').slideToggle('slow');

         return false
    });

});

工作演示

于 2013-09-25T12:14:18.363 回答
1

试试这个,在 if 语句中显示/隐藏

   if (jQuery('#service_container').is(':visible')) {
       jQuery(this).text('View Service Record');
       jQuery('#service_container').hide('slow');
   } else {
       jQuery(this).text('Hide Service Record');
       jQuery('#service_container').show('slow');
   }

演示

于 2013-09-25T12:03:12.453 回答
1

问题是在提出问题时“#service_container”是可见的,因为在slideToggle()完成之前它是不可见的。一种解决方案是将更改名称的逻辑作为要在slideToggle()完成后运行的函数传递。

...
var changeText = function() { <visibility text change logic> };
jQuery('#service_container').slideToggle('slow', changeText);
...

编辑:参考保存的小提琴。

完整代码:http: //jsfiddle.net/rqGBb/1/

如果您希望文本在单击时立即更改,您必须自己在变量中跟踪“显示/隐藏”状态,挂起元素,或测试外部if块中的可见性。

于 2013-09-25T12:06:46.690 回答
1

尝试使用“on”事件来对任何事件进行未来更改,如下所示

 jQuery('#view_service').on("click",function() {

             // your code..
}
于 2013-09-25T12:02:20.773 回答
1
if (jQuery('#view_service').html()=="View Service Record") {

小提琴:http: //jsfiddle.net/S6CwT/2/

我比较html的#view_service

于 2013-09-25T12:05:19.587 回答