[英]how to hide <select> element by onchange
I have an element which is set to display:none in css. 我有一个元素设置为在CSS中显示:none。 When the parent element gets clicked then the select appears through
当父元素被点击时,选择通过
document.getElementById('selectId').style.display = 'block';
Now I want that after some option is selected, the selector disappears. 现在,我希望选择某些选项后,选择器消失。
When calling style.display = 'none'
from onchange then it blinks for a fraction of a second and is again visible. 当从onchange调用
style.display = 'none'
,它会闪烁一秒钟,然后再次可见。 I even checked with console.log(obj.style.display)
and indeed the display changes quick. 我什至用
console.log(obj.style.display)
进行了检查,实际上显示变化很快。
How can I achieve this behavior: display = 'none'
by onchange
? 如何实现此行为:通过
onchange
display = 'none'
?
Pure JavsScript or JQuery does not matter 纯JavsScript或JQuery无关紧要
Edit: It looks like the onchange
event on the <select>
triggers the onclick
for the parent which resets the display to 'block'. 编辑:看起来
<select>
上的onchange
事件触发了父级的onclick
,从而将显示重置为“阻止”。
Code and Solution : on the suggestion from @AndyG I modified the function which gets called by the onchange event like this: 代码和解决方案 :根据@AndyG的建议,我修改了onchange事件调用的函数,如下所示:
function selChanged(obj) {
$(obj).click(function(event){
event.stopPropagation();
});
obj.style.display = 'block';
}
And now it wont trigger the parent 'onclick' anymore. 现在,它不再触发父级“ onclick”了。 Here the html code:
这里的HTML代码:
<td onclick="showSelect(selId)">
<select id="selId" onchange="selChanged(this)">
<option>
....
</option>
</td>
If the selection is changed by clicking an option, this click event will bubble up to the parent element, causing the select to reappear. 如果通过单击选项更改选择,则此click事件将冒泡到父元素,从而导致重新出现选择。
event.stopPropagation();
in the change event will prevent this bubbling to the parent. 在change事件中将阻止这种冒泡给父对象。
Whit jQuery.. 惠特jQuery ..
$('#selectId').hide()
to hide it $('#selectId').hide()
隐藏它
$('#selectId').show()
to show it $('#selectId').show()
显示它
Try this: 尝试这个:
$(function() {
$('select').on('change', function() {
$(this).hide();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.