gpt4 book ai didi

html - 选择元素 - 防止选择改变

转载 作者:太空宇宙 更新时间:2023-11-04 15:33:36 25 4
gpt4 key购买 nike

如何取消组合框 (SELECT) 元素的更改事件。 HTML SELECT 元素没有 onbefore 或 onchanging 事件。如果我把:

<SELECT onchange="return false;">
<OPTION value=a>A</OPTION>
<OPTION value=b>B</OPTION>
</SELECT>

事件没有取消。

最佳答案

您需要保存 <select> 的原始值某处。以便您可以将值改回。

取消事件,只会那样做。它只是取消事件,不会更改值。

示例(使用 jQuery):

$(function(){
$('select').each(function(){
$(this).data('selected', $(this).val()); // back up value
}).change(function(){
if(confirm('Are you sure you want to change the element?')){
$(this).data('selected', $(this).val()); // back up new value
}
else{
$(this).val($(this).data('selected')); // restore old value
}
});
});

演示:http://jsfiddle.net/pL2B4/

纯 JavaScript 解决方案(无 jQuery):

var select = document.getElementsByTagName('select');
for (var i = 0, len = select.length; i < len; i++) {
var el = select[i];
el.setAttribute('data-selected', el.value);
el.addEventListener('change', function() {
if (confirm('Are you sure you want to change the element?')) {
el.setAttribute('data-selected', el.value);
}
else {
el.value = el.getAttribute('data-selected');
}
});
}​

演示:http://jsfiddle.net/pL2B4/1/

关于html - 选择元素 - 防止选择改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11227731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com