How to make a permanent change to an element after

2019-09-02 05:34发布

问题:

I have the following jQuery code:

function showResult(str)
{
if (str.length == 0)
{
    $('#mySearch').html('');
    return;
}
else
{
    $('#mySearch').load('search/'+str,function(){
        $('#mySearch').css({
            'background-color': 'white',
            'width': '250px',
            'position': 'absolute',
            'right': '0'
        })
    });
}

$(document).click(function(event) {
if ( !$(event.target).hasClass('mySearch'))
{
     $('#mySearch').html('');
     $('#main_search').val('');
}
});

$(document).keydown(function(e){
    if (e.keyCode == 40) { 
       $('#mySearch tr.myRow:first').addClass("a_classy_class");
       return false;
    }
});
}

When I press the down arrow key the class 'a_classy_class' is added to the tag with id 'myRow'. However, as soon as I stop pressing the down arrow key the class is removed. How do I make the change permanent, so that after I stop pressing the down arrow key the change holds?

回答1:

In addition to the other suggestions, if the page is reloaded, your changes will not persist.



回答2:

Something else in your code is removing the class, or replacing the row with one that doesn't have it. Absent that, there's nothing that will magically remove the class from the row. Proof

Your #anID tr#myRow:first selector suggests that you may have issues with your HTML. An ID selector always selects a unique element, because id values must be unique on the page. So there's no need for the :first part of #myRow:first. So perhaps that has something to do with it, but I'm guessing at this point.