rub*_*ken -3 javascript jquery
使用select2插件(http://select2.github.io/select2/)
这将搜索$ choicestring变量的所有选项值,然后选择找到的值.如果它搜索超过200个选项值大约需要5-6秒......我试图减少这个.
有没有办法加快我的搜索元素包含字符串代码?
使用for循环而不是$ .each会更好吗?
jQuery的:
$('#selectbutton').click(function() {
var selectstring = $('#selectstring').val();
if (!selectstring.trim())
return false;
stringVal.push($('#projadd\\[\\]').val());
$('#projadd\\[\\]').find('option').each(function(){
if($(this).is(':contains(' + selectstring + ')')){
stringVal.push($(this).val());
}
$('#projadd\\[\\]').val(stringVal).trigger("change");
});
$('#selectstring').val('');
});
Run Code Online (Sandbox Code Playgroud)
这里的问题不仅仅是.each()你的代码.当你不需要它时,你正在创建很多jQuery对象.当它应该在元素之外时,您还要在元素中多次分配一个值.
当你可以轻松地做到香草时尝试避免使用jQuery.也尝试避免,:contain因为它是一个昂贵的选择器.
使用看起来像这样的代码:
$('#selectbutton').click(function() {
var selectstring = document.getElementById('selectstring').value; //Reduced the number of function call and doesn't create a jQuery object.
if (!selectstring.trim())
return false;
var $projadd = $('#projadd\\[\\]');//You use it more than 1 time? Cache it
stringVal.push($projadd.val());
$projadd.find('option').each(function(){
if(this.textContent.indexOf(selectstring) > -1){ //Don't use :contains, use native Javascript methods
stringVal.push(this.value); //Do not create jQuery object, acces value property. Accessing properties is always faster than calling a function.
}
});
$projadd.val(stringVal).trigger("change"); //Move it out of the .each, you only need to set the value once.
document.getElementById('selectstring').value = ''; //Same reason as above.
});
Run Code Online (Sandbox Code Playgroud)