2017-01-12 1 views
0

Я использую версию с открытым исходным кодом для мобильных устройств (версия 0.29.2). Я создал собственный рендерер, который создает скрытый элемент/элемент SPAN в каждой строке. Когда ввод завершается с ошибкой, я использую jQuery для программного отображения/отображения значка SPAN/значка, чтобы он отображался в правой части ячейки. Он отлично работает, но, к сожалению, когда я ввожу недопустимое значение в другую ячейку, значок из первой ячейки исчезает. Предпочтительное поведение заключается в том, чтобы все значки были видны в ячейках, где существует проблема проверки.Handsontable - Невозможно сохранить элемент html, созданный настраиваемым визуализатором, видимым

Вопрос: Есть ли способ сохранить все значки видимыми?

Если это невозможно, можно ли по-разному манипулировать отображением изображения после проверки? Как видно из приведенного ниже кода (и моего примера jsfiddle), я не использую встроенные handsontable hookation. Со встроенной проверкой я не могу добавить значок, как я хочу - я могу переопределить стиль недопустимой ячейки по умолчанию, используя invalidCellClassName.

Я создал простой пример с инструкциями демонстрируют мой вопрос: http://jsfiddle.net/4g3a5kqc/15/

var data = [ 
    ["1", "abc"], 
    ["2", "def"], 
    ["3", "ghi"], 
    ["4", "jkl"] 
], 
container = document.getElementById("example"), 
hot1;  

// This function is a custom renderer that creates a hidden SPAN element/ 
// icon. In this example, when a user changes the value, the SPAN element 
// icon will appear. 
function customRenderer(instance, td, row, col, prop, value, cellProperties)    { 
    td.innerHTML = value + 
     '<span id="account-code-error-' + row + '-' + col + '" class="account-code-error ' + 
     'glyphicon glyphicon-exclamation-sign text-warning jzb-icon-md pull-right" ' + 
     'style="font-size: large; cursor: pointer; display: none;"></span>'; 
} 

var hot1 = new Handsontable(container, { 
data: data, 
rowHeaders: true, 
colHeaders: true, 
stretchH: 'all', 
cells: 
    function (row, col, prop) { 
     var cellProperties = {}; 
     if (col == 0) { 
      cellProperties.renderer = customRenderer; 
     } 
     return cellProperties; 
    }  
}); 

hot1.addHook('afterChange', afterChange); 

// Show the SPAN tag with the icon 
// in the right-hand side of the cell. 
function afterChange(changes, source) { 
    console.log(changes, source); 

if (source == 'edit' || source == 'autofill') { 
    $.each(changes, 
     function (index, element) { 
      var change = element; 
      var rowIndex = change[0]; 
      var columnIndex = change[1]; 
      var oldValue = change[2]; 
      var newValue = change[3]; 

      console.log(oldValue, newValue, rowIndex, columnIndex, change); 

      if (columnIndex != 0) { 
       return; 
      } 

      if (newValue >= 0) { 
       return; 
      } 

      var cellProperties = hot1.getCellMeta(rowIndex, hot1.propToCol(columnIndex)); 

      var td = hot1.getCell(rowIndex, columnIndex, true); 
      var span = td.getElementsByTagName("span"); 
      $("#" + span[0].id).show(); 
     }); 
    } 
} 

ответ

1

Благодаря customRenderer() вызываются после каждого изменения мы должны хранить где-то клетку с пролетами видимыми и проверять его на рендеринг. С другой стороны, если диапазон не должен быть видимым (ввод действителен), нам нужно удалить его из массива ячеек с видимыми интервалами. Рабочая вилка: http://jsfiddle.net/8vdwznLs/

var data = [ 
    ["1", "abc"], 
    ["2", "def"], 
    ["3", "ghi"], 
    ["4", "jkl"] 
], 
container = document.getElementById("example"), 
hot1, 
visibleSpans = [];  

// This function is a custom renderer that creates a hidden SPAN element/ 
// icon. In this example, when a user changes the value, the SPAN element 
// icon will appear. 
function customRenderer(instance, td, row, col, prop, value, cellProperties)    { 
if (visibleSpans.indexOf(td) > -1) { 
    td.innerHTML = value + 
     '<span id="account-code-error-' + row + '-' + col + '" class="account-code-error ' + 
     'glyphicon glyphicon-exclamation-sign text-warning jzb-icon-md pull-right" ' + 
     'style="font-size: large; cursor: pointer;"></span>'; 
} else { 
    td.innerHTML = value + 
     '<span id="account-code-error-' + row + '-' + col + '" class="account-code-error ' + 
     'glyphicon glyphicon-exclamation-sign text-warning jzb-icon-md pull-right" ' + 
     'style="font-size: large; cursor: pointer; display: none;"></span>'; 
} 
} 

var hot1 = new Handsontable(container, { 
data: data, 
rowHeaders: true, 
colHeaders: true, 
stretchH: 'all', 
cells: 
    function (row, col, prop) { 
     var cellProperties = {}; 
     if (col == 0) { 
      cellProperties.renderer = customRenderer; 
     } 
     return cellProperties; 
    }  
}); 

hot1.addHook('afterChange', afterChange); 

// Show the SPAN tag with the icon 
// in the right-hand side of the cell. 
function afterChange(changes, source) { 
    console.log(changes, source); 

if (source == 'edit' || source == 'autofill') { 
    $.each(changes, 
     function (index, element) { 
      var change = element; 
      var rowIndex = change[0]; 
      var columnIndex = change[1]; 
      var oldValue = change[2]; 
      var newValue = change[3]; 
      var td = hot1.getCell(rowIndex, columnIndex, true); 

      console.log(oldValue, newValue, rowIndex, columnIndex, change); 

      if (columnIndex != 0) { 
       return; 
      } 

      if (newValue >= 0) { 
       var indexOfSpan = visibleSpans.indexOf(td); 
       if (indexOfSpan > -1) { 
        visibleSpans.splice(indexOfSpan, 1); 
        hot1.render(); 
        return; 
       } 
       return; 
      } 

      var cellProperties = hot1.getCellMeta(rowIndex, hot1.propToCol(columnIndex)); 

      visibleSpans.push(td); 
      var span = td.getElementsByTagName("span"); 
      span[0].setAttribute('style', ''); 
     }); 
    } 
} 
Смежные вопросы