解决选项标签的onclick事件 [英] Work around for onclick event of option tag

查看:58
本文介绍了解决选项标签的onclick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页上有一个多选下拉菜单,并有一个复选框,允许用户选择列表中的所有项目.

I have a multi-select drop-down on my web page and a checkbox to allow user to select all items in the list.

<select id="itemsList" multiple="true" size="3"></select>
<input type="checkbox" id="bSelectAll" onclick="selectAllItems();" />Select all

单击复选框将选择列表中的所有项目.现在,当我单击列表中的一个项目时,该项目将保持选中状态,而取消选择所有其他项目.我想要完全相反的行为.单击某个项目后,应取消选择该项目,而其他所有项目都应保持选中状态.

Clicking the checkbox selects all items in the list. Now when I click on one of the items in the list, that item remains selected while everything else is deselected. I want exact opposite behavior. When an item is clicked, that item should get deselected while everything else should remain selected.

我知道我们可以通过按住Ctrl键并单击某个项目来获得此行为.但是,要求它应该在正常点击时发生.

I know we can get this behavior by ctrl+clicking on an item. However, requirement is that it should happen on normal click.

我试图检查选项标签的onclick,但是似乎它不符合标准,因此仅受一部分浏览器支持.

I tried to check onclick of an option tag but it seems that it is not according to standards and hence supported by only a subset of browsers.

我无法通过使用select标签的onclick和onchange事件来完成此操作.

I could not accomplish this by using onclick and onchange events of select tag.

当未选中复选框时,行为应保持一致.简而言之,应始终单击选项标签.

The behavior should be consistent when checkbox is not checked. In short clicking on an option tag should always toggle its selection.

如果我使用复选框列表而不是选择框,则这将是默认行为.但是,有什么办法可以解决目前的问题?

This would be the default behavior if I use a list of checkboxes instead of select box. However, is there any way of doing this with what I have as of now?

推荐答案

一种解决方法是使用数组来记录选择/取消选择的内容,并在每次用户单击时重新构建您的选项.

One way to do it is using an array to keep record what been selected/deselected, and rebuild your options everytime user click.

js:

var record = [];

var selectAllItems = function (target) {
    //toggle all options here and keep a record in "record" array ...
}

var doTheMagic = function(target){
    record[target.selectedIndex] = ! record[target.selectedIndex];
    rebuildOptions();

}

var rebuildOptions = function (){
    var itemsList = document.getElementById('itemsList');
    for (var i=0;i<record.length;i++){
            itemsList.options[i].selected = record[i];
    }

}

html:

<select id="itemsList" multiple="true" size="3"  onclick="doTheMagic(this)">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="audi">Audi</option>
</select>
<input type="checkbox" id="bSelectAll" onclick="selectAllItems(this)" />Select all

jsFiddle演示: http://jsfiddle.net/3A9Xs/3/

jsFiddle demo: http://jsfiddle.net/3A9Xs/3/

这篇关于解决选项标签的onclick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆