有一个DIV元素(标识:容器),其中附加了mousedown事件处理程序。然后,我使用document.createElement(...)和append(...)将select元素添加到其中。 问题是,当我单击选择元素的箭头时,下拉列表没有打开。 请注意,容器元素是现有网页/ crm的一部分。无法修改。
// container:
$("#container").on('mousedown.something', function (event) {
event.preventDefault();
// some other code
});
// append a select to the container
var numbers = ["Numbers", "1", "2", "3"];
var list = document.createElement('select');
list.setAttribute("id", "dropdown");
for (var i = 0; i < numbers.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = numbers[i];
opt.value = numbers[i];
list.appendChild(opt);
}
$('#container').append(list);
jsfiddle: https://jsfiddle.net/tomsx/8tLjcgbh/
答案 0 :(得分:1)
您可以在e.stopPropagation()
鼠标按下事件中使用select
$("#container").on('mousedown.something', function(event) {
event.preventDefault();
console.log('MouseDown');
// some other code
});
var numbers = ["Numbers", "1", "2", "3"];
var list = document.createElement('select');
list.setAttribute("id", "dropdown");
for (var i = 0; i < numbers.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = numbers[i];
opt.value = numbers[i];
list.appendChild(opt);
}
$('#container').append(list);
//stop the container mousedown from the created select
$('#container').on('mousedown' , '> select' , function(e){
e.stopPropagation();
});
#container {
width: 200px;
margin: auto;
border: 3px solid #73AD21;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">Click me</div>
答案 1 :(得分:0)
您的事件也会在选择项(属于容器的一部分)上触发,因此仅当在容器元素上单击时才需要触发鼠标按下
{{1}}
答案 2 :(得分:0)
参考:https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
因此,您需要在addEventlistener中设置 passive:true
var numbers = ["Numbers", "1", "2", "3"];
var list = document.createElement('select');
list.setAttribute("id", "dropdown");
for (var i = 0; i < numbers.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = numbers[i];
opt.value = numbers[i];
list.appendChild(opt);
}
$('#container').append(list);
$("#container").on('mousedown.something', function (event) {
event.preventDefault();
// some other code
},{passive:true});