对于没有任何数据的选项值,我希望将游标属性从指针更改为默认值。我为此制作了一张 map ,用于跟踪选项值和其中的数据内容。这是我的代码的样子:
var newDataMap = {};
for (var i in payload) {
newDataMap[payload[i]data.year] = payload[i].data;
}
var year_html = '<option value = "all">All Years</option>';
for (var i in finYearTag) {
Object.keys(newDataMap).forEach(function eachKey(key) {
if(key == i) {
year_html += '<option value = "' + i + '"style = "cursor: pointer">' + finYearTag[i].name + '</option>';
}
else {
year_html += '<option value = "' + i + '"style = "cursor: default">' + finYearTag[i].name + '</option>';
}
});
}
$('#filterYear').html(year_html);
<select class="filt" id="filterYear" style="width: 180px;"></select>
选择选项是使用 select2 动态填充的,并且工作正常。我只是无法按预期更改光标样式。请帮忙。
最佳答案
您可以模拟一个选择框,而不需要 select2 插件。我使用一个类模拟了有/没有数据的选项。希望这提供了一个有效的替代方案。
我在源代码中记录了很多。如果有任何疑问,请告诉我。
const hasClass = (element, cls) => {
return (element.className).indexOf(cls) > -1;
}
const toggleSelect = (target) => {
const neighbor = target.nextElementSibling; // Get reference to options list
neighbor.classList.toggle("open"); // Show options
}
const selectedOption = (target) => {
const value = target.innerHTML; // Read HTML selected option
const selectedText = document.getElementsByClassName("selected")[0];
selectedText.innerHTML = value; // Set selected option in select box
const hiddenInput = document.getElementById("sel");
hiddenInput.value = value; // Set selected option in hidden input field
toggleSelect(selectedText); // Hide options
}
/*
A single event listener is added to the document. Once anything is clicked, it is
determined if any action needs to be taken.
This works also if any data is loaded dynamically.
*/
document.addEventListener('click', (event) => {
if (event.target.matches('.selected')) {
toggleSelect(event.target);
}
if (event.target.matches('.has-data')) {
selectedOption(event.target);
}
}, false);
.container {
display: flex;
flex-wrap: wrap;
width: 25%;
}
.selected {
border: thin solid darkgray;
border-radius: 5px;
background: lightgray;
display: flex;
align-items: center;
cursor: pointer;
height: 1.5em;
margin-bottom: .2em;
padding-left: .5em;
min-width: 150px;
position: relative;
}
.selected:after {
font-family: FontAwesome;
content: "\f0d7";
margin-left: 1em;
position: absolute;
right: .5em;
}
.options {
display: none;
margin: 0;
padding: 0;
}
.options.open {
display: inline-block;
}
li {
display: flex;
justify-content: flex-start;
align-items: center;
cursor: pointer;
}
li:not(.has-data) {
cursor: default;
color: lightgray;
}
li>img {
margin-right: 1em;
}
<form>
<input type="hidden" id="sel">
<div class="container">
<div class="selected">Select an option</div>
<ul class="options">
<li class="option has-data">Option 1</li>
<li class="option">Option 2</li>
<li class="option has-data">Option 3</li>
</ul>
</div>
</form>
关于javascript - Select2 下拉光标属性更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52114271/