我正在设计一个页面,它以以下结构显示员工详细信息:
用户可以单击详细信息框中的任意位置,该复选框将随着详细信息的 className 的更改而被选中 <div>
框。
我面临的问题是,当我单击详细信息框中的任意位置时,它工作正常。但是当我单击复选框时,它只会更改类名,但不会对复选框进行任何更改。
还有一个条件,少数用户可以一次选择有限的员工,也很少有人可以选择全部员工。
我已将 myClick() 函数分配给外部 <div>
盒子(有红色边框的)
其功能是:
var selectedCount = 0;
myClick = function(myObj,event)
{
var trgt =(event.srcElement) ? event.srcElement : event.target;
tgName = trgt.tagName;
//following statement gives me correct details element event though i clicked on any child tags
theElem = (tgName == 'DIV') ? trgt : ( (tgName == 'B') ? trgt.parentNode.parentNode : trgt.parentNode);
if(allowed_selection == 'unlimited')
{
if(theElem.className == 'details_clicked')
{
theElem.className = 'details';
theElem.getElementsByTagName('input')[0].checked = false;
}
else if(theElem.className == 'details_hover')
{
theElem.className = 'details_clicked';
if(tgName != 'INPUT') theElem.getElementsByTagName('input')[0].checked = true;
}
}
else
{
if(theElem.className == 'details_clicked')
{
theElem.className = 'details';
theElem.getElementsByTagName('input')[0].checked = false;
selectedCount--;
}
else if(theElem.className == 'details_hover')
{
if(selectedCount == allowed_selection ) return false;
theElem.className = 'details_clicked';
//i think, this is the suspicious area for errors
theElem.getElementsByTagName('input')[0].checked = true;
selectedCount++;
}
}
return false;
};
最佳答案
问题是函数中的这些返回行:
return false;
当您将事件连接到执行操作的表单元素(例如复选框或按钮)时,返回 false 将阻止该默认操作。它会阻止事件正常发生。
您可以在函数顶部尝试类似的操作:
var returnValue = (tgName == 'INPUT' && trgt.type == "checkbox") ? true : false;
然后在调用“return”时,使用:
return returnValue;
如果返回 true,则允许复选框正常运行并选中/取消选中自身。
关于Javascript:如何使此功能适用于点击效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5061467/