【问题标题】:bootstrap dropdown doesn't work as expected引导下拉菜单无法按预期工作
【发布时间】:2017-11-30 12:53:40
【问题描述】:

我正在使用引导程序的下拉功能,并且我在容器中有这个下拉菜单,但在外部我有包装器,它对同一事件(onclick)做出反应,所以我这样做了

e.stopPropagation();

因为我不想在单击下拉按钮时对包装器中的事件做出反应。不幸的是,这段代码也停止了我的下拉事件。是否可以避免这种行为并只显示下拉列表而不发出警报? https://jsfiddle.net/hms5265s/

【问题讨论】:

  • 只需将您的e.stopPropagation() 添加到包装函数中即可。

标签: javascript jquery twitter-bootstrap dom twitter-bootstrap-3


【解决方案1】:

这是我的解决方案。

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

【讨论】:

  • 这根本没有帮助。陈述是错误的,而且这两种情况都是无用的
  • @stwosch 告诉我你到底想要什么?
  • 我想显示打开的下拉列表而不在包装器中调用警报
  • @stwoch 意味着默认情况下,每当您加载页面时,您都需要打开下拉菜单?
  • 不,我想在点击事件中显示
【解决方案2】:

如果您希望在包装器的单击事件而不是下拉列表本身的单击事件上调用警报,您可以尝试这样的操作

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.
});

这是JSFiddle

如果您也不想为下拉列表分配 Id,您也可以检查类。

【讨论】:

  • @Stwosch 这不起作用还是不是您想要的?
【解决方案3】:

这是我的解决方案

    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/

更新的解决方案:

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/

【讨论】:

  • 你在.dropdown-menu上做stopPropagation,也就是
      ...没有事件
猜你喜欢
  • 1970-01-01
  • 2018-07-04
  • 2017-04-12
  • 2020-05-01
  • 2017-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多