javascript - 在下拉列表中,将 optgroup 名称设置为 JS 在 Firefox 中不起作用的选定选项文本
问题描述
我有 javascript 将select
下拉列表中显示的选定文本设置为选定选项的<optgroup>
标签,但是当下拉列表打开时,它会将存储的文本显示data-content
为标签下的选项文本<optgroup>
。它在 Chrome 中运行良好,但在 Firefox 中中断。在 Firefox 中单击选择时,它开始打开和关闭的速度非常快,无法进行选择。我注意到,当我注释掉$(this).blur
闪烁停止的部分时,js 显然会中断。谢谢你尽你所能的帮助!
您可以在此处查看 jsfiddle
这是HTML:
<select id="car_choice">
<optgroup label="Truck">
<option data-value="truck" data-title="Truck" data-content="A description of a truck">
Truck
</option>
</optgroup>
<optgroup label="Car">
<option data-value="car" data-title="Car" data-content="A description of a car">
Car
</option>
</optgroup>
</select>
这是JS:
$('#car_choice option:selected').html($('#car_choice option:selected').attr('value'));
$("#car_choice").on('change mouseleave', function(){
$('#car_choice option').each(function(){
$(this).html($(this).attr('data-title'));
});
$('#car_choice option:selected').html($('#car_type_choice option:selected').attr('data-title'))
$(this).blur();
});
$('#car_choice').on('focus', function(){
$('#car_choice option').each(function(){
$(this).html( $(this).attr('data-content'));
});
});
解决方案
一种粗略的解决方案,但我在这里解决了
$('#assignment_type_choice option:selected').html($('#assignment_type_choice option:selected').attr('value'));
var browser;
if (navigator.userAgent.match(/Chrome/i)) {
browser = "chrome";
}
else {
browser = "other";
}
$("#assignment_type_choice").on('click mouseup', function(){
if(browser === "other"){
$('#assignment_type_choice').each(function(){
$(this).text($(this).attr('data-title'));
});
$('#assignment_type_choice option:selected').html($('#assignment_type_choice option:selected').attr('data-title'))
};
});
$("#assignment_type_choice").on('change mouseleave', function(){
console.log("browser is " + browser)
if(browser === "chrome"){
$('#car_choice option').each(function(){
$(this).text($(this).attr('data-title'));
});
$('#assignment_type_choice option:selected').html($('#assignment_type_choice option:selected').attr('data-title'))
};
});
$('#assignment_type_choice').on('mousedown', function(){
$('#assignment_type_choice option').each(function(){
$(this).text( $(this).attr('data-content'));
});
});
推荐阅读
- css - TYPO3 8.7.22 页面 UID CSS
- bash - 自动化 docker 以运行测试脚本
- android - Android Studio 使用 Flutter 获取模拟器名称
- html - Safari 不显示显示:网格
- java - Eclipse 无法识别同一项目中生成的类的导入
- oracle - 使用 Utl_file 进行 Oracle UTF8 文件编码
- ios - 测试应用程序在我的 iPhone 上构建几天后会崩溃
- linux - 仅解析来自 resolvectl 的 IP 地址
- sharepoint - 使用自定义站点模板进行自定义流程部署
- c# - SSH 连接到树莓派