我有一个已停用选项的选择。如果用户单击该选项,则需要在警报中返回该选项的文本。
jQuery('#test.option').click(function() {
alert(jQuery(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='test'>
<option>AAAAAAAA</option>
<option>BBBBBBBB</option>
<option disabled="disabled">CCCCCCCC</option>
</select>
这只是一个例子,尽管我有实际计划。我有一个后端,我在其中创建每个选项的select,在那里我可以指定应显示每个选项的文本,我需要该选项的id或文本,以找到要渲染到DOM但隐藏的相应文本
但是似乎无法将click事件添加到选项中。
编辑:这不是重复的,因为我说的是选择选项而不是输入。
答案 0 :(得分:1)
在这种情况下,我唯一想到的方法是删除disabled
并使用CSS创建效果。然后阻止用户选择使用JS。在尝试解决JS问题时,我并没有做很多事情来操纵CSS,但是您可以继续并围绕CSS进行工作。
$(document).ready(function() {
var previous;
$("#test").on('focus', function() {
// Store the current value on focus and on change
previous = this.value;
}).change(function() {
// If it's the option we want to disable, we set the select as the previous value
if ($(this).val() == 3) {
alert("Nope!")
$('#test').val(previous);
} else {
// Make sure the previous value is updated
previous = this.value;
}
});
});
.isDisabled {
background-color: rgb(229, 229, 229) !important;
opacity: 0.5;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='test'>
<option>1</option>
<option>2</option>
<option class="isDisabled">3</option>
</select>
答案 1 :(得分:1)
您可以使用此替代方法
var lastSel;
$("#test").on('focus', function () {
if ($('option:selected', this).attr('data-disabled') != "true") {
lastSel = $("#test").prop('selectedIndex');
}
}).change(function() {
if ($('option:selected', this).attr('data-disabled') == "true") {
alert('Item is disabled')
$("#test").prop('selectedIndex', lastSel);
} else {
lastSel = $("#test").prop('selectedIndex');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="test">
<option>AAAAAAAA</option>
<option>BBBBBBBB</option>
<option data-disabled="true" style="color: grey">CCCCCC</option>
</select>