是否可以动态地向元素添加事件

时间:2017-04-25 09:24:18

标签: javascript jquery edmx

我有一个EDM模型,我正在尝试为它生成动态UI,但它不能将事件添加到超过1个选择。

换句话说,它只适用于1选择而不是更多。

        function addEvents(id) {
          $('body').on('click', '#entities_' + id, function(event) {
            var $e = $(event.target);
            var entityIndex = $("#entities_" + id + " option:selected").index(); //$e.val();
            var entity = entities[entityIndex - 1];
            var columns = entity.property; // if index is not -1


            var $entities_cols = $("#entities_" + id + "_cols").empty();
            $.each(columns, function(index, e) {
              var selectColumnHtmlId = 'selectcolumn_' + e.name;
              var $selectColumnLabel = $('<label />', {
                'for': selectColumnHtmlId,
                text: e.name
              });
              $selectColumnLabel.appendTo($entities_cols);
              $('<input />', {
                type: 'checkbox',
                id: selectColumnHtmlId,
                value: e.name
              }).prependTo($selectColumnLabel);
            });

            if (id <= config.expandLimit)
              addExpand(++id, entity.navigationProperty);
          });
        }

以下是完整示例 - https://jsfiddle.net/ntbkyuau/3/

1 个答案:

答案 0 :(得分:0)

通过改变它来实现它,

  function addEvents(id) {
          var $entities = $('#entities_' + id);
          $('body').on('click', $entities, function(event) {
            var $e = $(event.target);
            var entityIndex = $("#entities_" + id + " option:selected").index(); //$e.val();
            var entity = entities[entityIndex - 1];
            var columns = entity.property; // if index is not -1


            var $entities_cols = $("#entities_" + id + "_cols").empty();
            $.each(columns, function(index, e) {
              var selectColumnHtmlId = 'selectcolumn_' + e.name;
              var $selectColumnLabel = $('<label />', {
                'for': selectColumnHtmlId,
                text: e.name
              });
              $selectColumnLabel.appendTo($entities_cols);
              $('<input />', {
                type: 'checkbox',
                id: selectColumnHtmlId,
                value: e.name
              }).prependTo($selectColumnLabel);
            });

            if (id <= config.expandLimit)
              addExpand(++id, entity.navigationProperty);
          });
        }