简体   繁体   English

引导程序下拉菜单无法正常工作

[英]bootstrap dropdown doesn't work as expected

I'm using dropdown functionality of bootstrap and I have this dropdown in container, but in outside I have wrapper, which is reacting on the same event (onclick), so I do 我正在使用bootstrap的下拉功能,并且在容器中有此下拉菜单,但是在外部,我有包装器,该包装器对同一事件(onclick)做出反应,所以我

e.stopPropagation();

because I don't want to react on event in wrapper, when I'm clicking dropdown button. 因为当我单击下拉按钮时,我不想对包装器中的事件做出反应。 Unfortunately, this code also stops my dropdown event. 不幸的是,这段代码也停止了我的下拉事件。 Is it possible to avoid this behaviour and display only dropdown list, without alert? 是否有可能避免这种现象,仅显示下拉列表,而不会发出警报? https://jsfiddle.net/hms5265s/ https://jsfiddle.net/hms5265s/

Here is my solution. 这是我的解决方案。

document.querySelector('.container').addEventListener('click', (e) => {
    if($(e.target).is("#dropdown")){
    alert('work');
  }
  else{
    e.stopPropagation();}
});

If you want your alert to be called on the click event of the wrapper but not the click event of the dropdown iteself you can try something like this 如果您希望在包装程序的click事件上调用警报,而不在下拉菜单本身的click事件上调用警报,则可以尝试这样的操作

document.querySelector('#wrapper').addEventListener('click', (e) => {
    var source = event.target || event.srcElement;
console.log(source.id);
if (source.id !== 'someId') {
// do some stuff
    alert("I don't want this alert");
}
// you can stop the even propagation here if you want to.
});

Here is a JSFiddle 这是一个JSFiddle

If you also don't want to assign an Id for your dropdown you can also check for a class. 如果您也不想为下拉菜单分配ID,则还可以检查一个类。

here is my solution 这是我的解决方案

    Element.prototype.hasClass = function(className){
        tClassName = this.className;
        return tClassName.match(".*[ ]?"+className+"[ ]?.*") ? true : false;
};

document.querySelector('#wrapper').addEventListener('click', (e) => {
    console.log('clicked' + e.target.hasClass('dropdown-toggle'));
        if(e.target.hasClass('dropdown-toggle')) return

    alert("I don't want this alert");
});

document.querySelector('.dropdown-menu').addEventListener('click', (e) => {
    e.stopPropagation();
});

https://jsfiddle.net/hms5265s/6/ https://jsfiddle.net/hms5265s/6/

updated solution: 更新的解决方案:

Element.prototype.hasClass = function(className){
        tClassName = this.className;
        return tClassName.match(".*[ ]?"+className+"[ ]?.*") ? true : false;
};

document.querySelector('#wrapper').addEventListener('click', (e) => {
        if(e.target.hasClass('dropdown-toggle')) return
    alert("I don't want this alert");
});

document.querySelector('.container').addEventListener('click', (e) => {
if(! e.target.hasClass('dropdown-toggle')){
    e.stopPropagation();
}
});

https://jsfiddle.net/hms5265s/12/ https://jsfiddle.net/hms5265s/12/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM