【问题标题】:How to know what element triggered the openind of a bootstrap modal如何知道是什么元素触发了引导模式的 openind
【发布时间】:2020-09-25 03:34:30
【问题描述】:

我在一个表单中有两个产品下拉列表。如果所选选项是第一个选项(值为 -1),则打开一个模式,用户可以在其中保存新产品。

在模式关闭时,我更新了两个下拉菜单,并希望仅在触发模式打开的下拉菜单中自动选择新产品。我已经设法完成了有关保存、更新和自动选择的所有逻辑。问题是现在我在两个下拉菜单上自动选择,而不仅仅是在触发的下拉菜单上。

这就是我打开模式的方式:

if (select.value == '-1') {
    let modal = document.getElementById('newProductModal');        
    // set some properties on the modal
    $(modal).modal('show');

这是提交按钮上的点击事件监听器:

document.getElementById('saveNewProduct').addEventListener('click', function (e) {  
    // some stuff  
    document.querySelectorAll("select[id$='product']").forEach(item => {
        populateProducts(item, data.id);
    })
}

有什么想法吗?

【问题讨论】:

    标签: javascript jquery dom-events


    【解决方案1】:

    您可以使用变量来跟踪哪个下拉菜单触发了模态,或者在模态本身上设置data 属性,该属性可能包含下拉列表id 或其他唯一标识符。只需记住在提交后清除变量/数据属性的值以防止任何错误。

    可变方法

    let dropdownVal = null
    function handleSelect(){
      if (select.value == '-1') {
        let modal = document.getElementById('newProductModal');        
        // set some properties on the modal
        dropdownVal = -1
        $(modal).modal('show');
      }
    }
    
    document.getElementById('saveNewProduct').addEventListener('click', function (e) {  
        // some stuff  
        if(dropdownVal && dropdownVal===-1){
          document.querySelectorAll("select[id$='product']").forEach(item => {
            populateProducts(item, data.id);
          })
        }else{
         //...update pdt in dropdown 2
        }
    
    }
    

    数据属性方法

    function handleSelect(){
      if (select.value == '-1') {
        let modal = document.getElementById('newProductModal');        
        // set some properties on the modal
        $(modal').data('dropdown', -1);
        $(modal).modal('show');
      }
    }
    
    document.getElementById('saveNewProduct').addEventListener('click', function (e) {  
        // some stuff  
        if($(modal).data('dropdown')===-1){
          document.querySelectorAll("select[id$='product']").forEach(item => {
            populateProducts(item, data.id);
          })
        }else{
         //...update pdt in dropdown 2
        }
    
    }
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      • 2019-07-06
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多