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

标签 html

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

<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/

相关文章:

html - CSS "crop"图像,但垂直居中对齐

javascript - 单页导航出现问题 - 更新/突出显示事件状态并滚动到 anchor

javascript - 添加向下滚动 1 如果 div > 在 "x.top"或 "x.left"

Java HTML解析NullpointerException

html - CSS 中继承和特殊性的混淆

javascript - 使用 Javascript 打开随机帖子

html - 我怎样才能使高度 : "100%" work cross browser in CSS?

使用句点的 Html 相对路径

html - 使用手写笔功能时保持手写颜色值

javascript - 如何让总计显示在计算器中?