最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Cannot remove a class hidden by JavaScript - Stack Overflow

programmeradmin1浏览0评论

I would like hide a div when it is loaded and show it when a button is clicked, but what I get is that the div only shows for a short while and hides again. Am I doing it correctly with the CSS class or is there anything special about display:none;?

HTML


<div id="message">
    <div class="item-user hid">
        <a href="">something</a> 
    </div>

    <a class="btn-user" href="">button</a>
</div>

CSS


.hid {
    display: none; 
}

JS


<script>
    //jquery is loaded already

    $(document).ready(function(){

        $('#message .btn-user').click(function(){
            $('#message .item-user').removeClass('hid');
        });

    });
</script>

I would like hide a div when it is loaded and show it when a button is clicked, but what I get is that the div only shows for a short while and hides again. Am I doing it correctly with the CSS class or is there anything special about display:none;?

HTML


<div id="message">
    <div class="item-user hid">
        <a href="">something</a> 
    </div>

    <a class="btn-user" href="">button</a>
</div>

CSS


.hid {
    display: none; 
}

JS


<script>
    //jquery is loaded already

    $(document).ready(function(){

        $('#message .btn-user').click(function(){
            $('#message .item-user').removeClass('hid');
        });

    });
</script>
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Feb 17, 2014 at 10:43 TonyTonyTonyTony 1,41418 silver badges23 bronze badges 2
  • 1 Can you provide a jsFiddle? – RobinvdA Commented Feb 17, 2014 at 10:44
  • The problem is just as Felix has captured, his answer works well. @RobinvdA – TonyTony Commented Feb 17, 2014 at 11:31
Add a ment  | 

3 Answers 3

Reset to default 6

You need to use e.preventDefault() to prevent the default action of your anchor:

$('#message .btn-user').click(function(e){
    e.preventDefault();
    $('#message .item-user').removeClass('hid');
});

Fiddle Demo

use this http://jsfiddle/3Cp75/

for

<div id="message">
    <div class="item-user hid">
        <a href="">something</a> 
    </div>

    <a class="btn-user" href="">button</a>
</div>

why we are using preventdefault:

  **Prevent a submit button from submitting a form**

otherwise if you dnt want it remove href

link http://jsfiddle/3Cp75/1/

Update your anchor tag "href" attr to "javascript:void(0);". This will prevent the default action and leave it to manage the action with javacript.

Or you can go with the

event.preventdefault()

This also do same but you will handle the action in javascript function.

发布评论

评论列表(0)

  1. 暂无评论