Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

jquery hide() not working in chrome

I use jquery popup dialog, and in this dialog I have input and select box, i want to hide some options in select box, its worked in ff, but not worked in chrome .

<input type="text" onkeyup="search(this.value)" >

<select id="cl_sel_l"  multiple="multiple">
   <option value='2' id='c_2'>aa</option>
   <option value='3' id='c_3'>bb</option>
   <option value='4' id='c_4'>cc</option>
   <option value='5' id='c_5'>dd</option>
</select>
var clients = new Array();
clients[2] ='aa';
clients[3] ='bb';
clients[4] ='cc';
clients[5] ='dd';

function search(val) {
    for ( var i in clients) {
        if (clients[i].toLowerCase().search(val.toLowerCase()) == -1) {
            $("#cl_sel_l").find("#c_" + i).hide();
        } else {
            $("#cl_sel_l").find("#c_" + i).show();
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

display: none (which is what jQuery's hide() function does to matched elements) will not work for option elements in a reliable, cross-browser manner. Instead, you need to remove them from the DOM, and then add them back in after the search.

This is a little tricky, as you need to store the original order. I'd be tempted to just delete non-matches, and then restore. Something like this:

var clients = new Array();
clients[2] ='aa';
clients[3] ='bb';
clients[4] ='cc';
clients[5] ='dd';
var restore;

function search(val) {
    $('#cl_sel_l').html(restore);
    for ( var i in clients) {
        if (clients[i].toLowerCase().search(val.toLowerCase()) == -1) {
            $("#c_" + i).remove();
        }
    }
}

$(function() { restore = $('#cl_sel_l').html(); });

See this jsFiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...