简体   繁体   中英

Javascript change class onclick

Im just trying to get to grips with javascript / ajax / jQuery so Im building a ticket system for my website.

Anyway, I have a table at the top of the page;

    <table align="center" class="thinline" width="600" border="1" cellpadding="2" bordercolor="black">
    <tr class="subtopic" style="font-size: 15px;">
        <td><a onClick="javascript: ShowNewTickets()">New Tickets</a></td>
        <td><a onClick="javascript: ShowYourTickets()">Your Tickets</a></td>
        <td><a onClick="javascript: ShowPuplicTickets()">Public Tickets</a></td>
    </tr>
</table>

When the page loads I want "New Tickets" to have the class "selected". If they hover the mouse over any of the unselected menus then it has a highlighted effect. Once they click onto another link the "selected" class will be removed from the other TD and added to the new TD.

I have tryed onmouseover and onmouseout to do the highlight effect but it messes up when it comes to the link which is already highlighted.

I have also tryed,

    $('.off').live('mouseenter', function() {
    if ($(this).hasClass('selected') == false) {
        $(this).removeClass('off').addClass('highlighted');
    }
});

But that then keeps the TD highlighted.

Thanks for reading.

You should use :hover pseudo-class .

It will handle mouse over/out for you.

As Sergio Tulentsev mentioned, you should use the :hover pseudo class to handle the highlight effect. To handle the "selected" class, you could do something like this:

$('.subtopic').on('click', 'a', function(e) {
    $('.subtopic a').removeClass('selected'); // remove the class from all the links
    $(this).addClass('selected'); // add it to the clicked link
}

Note that I am using the new jquery function .on() instead of .click, .live or .delegate. The way .on() works, you will make sure you only bind events to the links in the .subtopic row. Using .on() also guarantees your events will still fire when adding new links dynamically to the DOM.

.toggleClass() ,它按照名称提示进行操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM