.parents().removeClass() not working

ⅰ亾dé卋堺 提交于 2019-12-06 10:33:28

You have a click handler on the .box element.

And inside it you have a click handler on the .cunload element.

Since the .cunload is nested in the .box both elements receive the click event when you press the close button, and so it re-opens.. (due to events bubbling up the DOM hierarchy)

Change your .cunload handler to

$('.cunload').click(function(e){
            e.stopPropagation();
            restoreBoxes();
            $(this).parents(".box").removeClass("expanded");
});

maybe this will work:

$(this).parents(".box").filter(".expanded").removeClass("expanded");

If I use this code:

$(".cunload").click(function() {
    $(this).parents(".box").removeClass("trx");
});

With this HTML:

<div class="box trx">
<div class="expandable">
    <span class="simple">
        <a class="cunload" href="#">Close</a>
    </span>
</div>
</div>

Then, it seems to work exactly as designed and you can see it work here: http://jsfiddle.net/jfriend00/Djjuz/. Click on the close link and see that the background color changes when the trx class is removed.

So, there must be something else in your code that you are not disclosing that makes it not work. Please include the exact code you use to trigger the function and perhaps explain better what you are trying to do and what you observe happening or not happening.

If you expect us to use the link to the working page, please describe where the relevant code is (there are a lot of JS files in that page) and describe what you click on and what you expect the result to be. So far, you've only told us that something doesn't work, but not given us enough context to figure out what exactly doesn't work, what code you're using to trigger it and how we could possibly reproduce the issue or see the issue ourselves. You have to help yourself here by giving us enough info if you want quality help.

Also, do you realize that when you pass a selector the the .parents("selector") method, that it limits the operation to only the parents that match that selector? So .parents(".box") will ONLY operate on the parent objects that have a class"box".

I think it works, but your script expands the boy again after clicking on the close button. You should change the header of your close event handler function to:

function(event) {
    event.stopPropagation();
    [...]

so that the same click event can not bubble up the document hierarchy.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!