How to make a permanent change to an element after using jQuery's .keydown()?

佐手、 提交于 2019-12-25 05:15:37

问题


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.



来源:https://stackoverflow.com/questions/9648683/how-to-make-a-permanent-change-to-an-element-after-using-jquerys-keydown

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