我使用以下 jquery 根据 php 脚本返回的值创建自动完成菜单。
这些是 PHP 返回的值。
["Site 4","Site 2","Site 1","*************","Site 6","Site 7","Site 0"]
这是我的自动完成功能的 jquery:
$( '#site' ).autocomplete({
source: 'siteCheck.php',
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
$('#site').val(ui);
}
});
这会将正确的结果返回到屏幕并显示 ****************
选项。不过,我想将该选项设置为粗体并停止从列表中选择它。
这可能吗?我尝试使用 jquery 禁用选择选项,但这似乎没有任何作用。
这不是另一张票的重复,他们询问如何在显示特定数量的结果后禁用条目。我想禁用一个特定条目。
最佳答案
我修改了one the examples在 jQuery 的官方网站上。它应该足够简单,可以适应您的数据。
其工作原理如下:
特性
disabled
数据数组 (projects
) 告诉自定义渲染逻辑是否禁用某个选项。我已经自定义了渲染器来设置类
ui-state-disabled
如果元素有disabled
则在选项上设置为true
。它还有助于设置background-color
灰色和font-weight
大胆。然后在
focus
事件处理程序,您return false
如果该项目被禁用。这可以防止 jQuery 在您向下导航时将项目填充到输入中。最后,关于
select
处理程序,再次,您阻止根据disabled
的值选择该值属性(property)。
var projects = [{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png",
disabled: false
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png",
disabled: true
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png",
disabled: false
}
];
$("#project").autocomplete({
minLength: 0,
source: projects,
focus: function(event, ui) {
if(ui.item.disabled) {
console.log("Preventing focus.");
return false;
} else {
return true;
}
},
select: function(event, ui) {
if(!ui.item.disabled) {
$("#project").val(ui.item.label);
} else {
console.log("Preventing selection.");
}
return false;
}
})
.autocomplete("instance")._renderItem = function(ul, item) {
return $("<li>")
.append("<div class='"+(item.disabled ? 'ui-state-disabled' : '')+"'>" + item.label + "<br>" + item.desc + "</div>")
.appendTo(ul);
};
.ui-menu-item-wrapper.ui-state-disabled {
background-color: #aaa;
font-weight: bold;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<input id="project">
关于javascript - 禁用 jQuery 自动完成中的选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46390785/