5

Tenho uma tabela chamada gridContudo. Nessa tabela, existe essa <td>: { width: 100, name: 'OBSERVACAO', index: 'OBSERVACAO', label: 'Observação'}]. O que eu preciso é criar um atributo title nessa< td>. Como eu faço? Se eu colocat isso: title: 'meu_title', simplesmente não funciona. Pequei isso, mas não entendi tudo:

$('#gridConteudo tr td:nth-child(15)').each(function (i) {
    if (i > 0) { //skip header
        var sContent = $(this).text();
        $(this).attr("title", $(this).html());
        //if (sContent.length > 20) {
        //    $(this).text(sContent.substring(0, 20) + '...');
        //}
    }
});

Não entendi bem essa linha:

tr td:nth-child(15)')

Como o conteúdo da <td>é muito grande, coloquei essa linha, mas não funcionou:

if (sContent.length > 20) {
   $(this).text(sContent.substring(0, 20) + '...');

Como eu estou tendo dificuldade para fazer funcionar, como um todo, creio que não funcionou devido a esses problemas. Não funcionou ele não mostrar mais de 20 linhas.

Abaixo a minha função que monta a table. Os exemplos que baixei, funcionam em uma table feita por html puro, mas quando aplico na table abaixo, não funciona, nada mesmo.

function CarregarGrid() {
            $('#gridConteudo').jqGrid({
                colModel: [{ width: 80, name: 'COD_OPERADORA', index: 'COD_OPERADORA', label: 'Operadora', formatter: GridOperadoraFormatter },
                           { name: 'NOM_OPERADORA', index: 'NOM_OPERADORA', hidden: true },
                           { width: 80, name: 'SITUACAO', index: 'SITUACAO', label: 'Situação' },
                           { width: 90, name: 'DT_EXCLUSAO_OPERADORA', index: 'DT_EXCLUSAO_OPERADORA', label: 'Dt. Exclusão Operadora', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "d/m/Y", newformat: 'd/m/Y' } },
                           { width: 130, name: 'COD_REDE', index: 'COD_REDE', label: 'Rede', formatter: GridRedeFormatter },
                           { name: 'NOM_REDE', index: 'NOM_REDE', hidden: true },
                           { width: 90, name: 'DT_EXCLUSAO_REDE', index: 'DT_EXCLUSAO_REDE', label: 'Dt. Exclusão Rede' },
                           { width: 120, name: 'COD_PRESTADOR_SUBSTITUTO', index: 'COD_PRESTADOR_SUBSTITUTO', label: 'Prestador Substituto', formatter: GridPrestadorSubstitutoFormatter },
                           { name: 'NOME_PRESTADOR_SUBSTITUTO', index: 'NOME_PRESTADOR_SUBSTITUTO', hidden: true },
                           { width: 115, name: 'DESC_MOTIVO_EXCLUSAO', index: 'DESC_MOTIVO_EXCLUSAO', label: 'Motivo Exclusão' },
                           { width: 95, name: 'DT_NOTIF_VOLUNTARIA', index: 'DT_NOTIF_VOLUNTARIA', label: 'Dt. Notificação Excl. Voluntária', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "d/m/Y", newformat: 'd/m/Y' } },
                           { width: 90, name: 'DT_LIMITE_ATD', index: 'DT_LIMITE_ATD', label: 'Dt. Limite Realização', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "d/m/Y", newformat: 'd/m/Y' } },
                           { width: 90, name: 'DT_LIMITE_REMESSA', index: 'DT_LIMITE_REMESSA', label: 'Dt. Limite Apresentação', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "d/m/Y", newformat: 'd/m/Y' } },
                           { width: 90, name: 'DT_LIMITE_RECURSO', index: 'DT_LIMITE_RECURSO', label: 'Dt. Limite Reapresentação', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "d/m/Y", newformat: 'd/m/Y' } },
                           { width: 90, name: 'DT_FIM_EXIBE_DIRECIONAMENTO', index: 'DT_FIM_EXIBE_DIRECIONAMENTO', label: 'Dt. Fim Exibe Site', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "d/m/Y", newformat: 'd/m/Y' } },
                           { width: 100, name: 'OBSERVACAO', index: 'OBSERVACAO', label: 'Observação'}],
                url: urlControle + '/GetPrestadorOperadora',
                mtype: 'POST',
                postData: { "pEXEC": function () { return $("#pEXEC").val(); }, "pCodPrestadorTS": function () { return $("#hidCodPrestadorTS").val(); } },
                jsonReader: { repeatitems: false, root: function (obj) { return obj.Items; } },
                datatype: "json",
                autowidth: true,
                shrinkToFit: false,
                forceFit: true,
                loadonce: true,
                loadError: function (xhr, st, err) { $.notificacoes.erro("@TopSaudeResource.notificacao_erro_transacao"); },
                loadComplete: function () {

                    if ($('#hidCodPrestadorTS').val() != '') {

                        var linhas = $("#gridConteudo").getDataIDs();

                        if (linhas.length <= 0) {
                            $('#divConteudo').hide();
                            $.notificacoes.erro("Prestador não está excluído em nenhuma Operadora e/ou Rede");
                        }
                        else {
                            $('#divConteudo').removeAttr('style');
                            $('#divConteudo').show();
                        }

                        $('table tbody tr td').each(function () {
                            var td = $(this);
                            var texto = td.text();
                            if (texto.length > 30) {
                                texto = texto.substr(0, 30) + '...';
                            }
                            td.attr('title', texto);
                        })
                    }
                }
            });

            $('#gridConteudo').jqGrid('setLabel', 'COD_OPERADORA', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'SITUACAO', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DT_EXCLUSAO_OPERADORA', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'COD_REDE', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DT_EXCLUSAO_REDE', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'COD_PRESTADOR_SUBSTITUTO', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DESC_MOTIVO_EXCLUSAO', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DT_NOTIF_VOLUNTARIA', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DT_LIMITE_ATD', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DT_LIMITE_REMESSA', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DT_LIMITE_RECURSO', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DT_FIM_EXIBE_DIRECIONAMENTO', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'OBSERVACAO', '', { 'text-align': 'left' });
        }

O toottip deve estar na coluna OBSERVACAO.

1

2 Respostas 2

2

Não entendi bem essa linha: 'tr td:nth-child(15)'

O seletor nth-child() te permite selecionar o elemento filho de um elemento pai, seja pelo índice, pela classe do elemento filho ou ainda por uma fórmula.

No seu caso '#gridConteudo td:nth-child(15)' você está selecionando a coluna no índice 15 de sua tabela.

Como o conteúdo da 'td' é muito grande, coloquei essa linha, mas não funcionou:

Para limitar a quantidade de caracteres, sua função está correta, apenas criei uma função e estou chamando ela em dois momentos, para alterar o texto da tabela e o title da tabela. Você também não precisa verificar se é ou não a primeira linha, se você possui o tbodye thead em sua tabela, é só adicionar na função.

Obs.: Você está utilizando a função attr do jQuery para alterar o atributo title, se for utilizar uma versão recente do jQuery, essa função foi alterada para prop.

Veja seu código refatorado:

$('#gridConteudo tbody td:nth-child(15)').each(function () {
    var sContent = $(this).text();
    //Alterar title
    $(this).attr("title", limitarCaracteres(sContent, 20));
    //Alterar coluna da tabela
    $(this).html(limitarCaracteres(sContent, 20));

    function limitarCaracteres(texto, qtde) {
        if (texto.length > qtde)
           texto = sContent.substring(0, qtde) + '...';
        return texto;
    });
});
2

O que eu preciso é criar um atributo title nessa <td>. Como eu faço?

Você pode fazer assim:

$('table tbody tr td').each(function() {
  var td = $(this);
  var texto = td.text();
  td.attr('title', texto);
  if (texto.length > 30) {
    texto = texto.substr(0, 30) + '...';
  }
  td.text(texto);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table class="table text-center">
  <thead>
    <tr>
      <td>Descrição</td>
      <td>Valor</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e os embaralhou para fazer um livro de modelos de tipos.
        Lorem Ipsum sobreviveu não só a cinco séculos, como também ao salto para a editoração eletrônica, permanecendo essencialmente inalterado.</td>
      <td>R$10</td>
    </tr>
    <tr>
      <td>Café</td>
      <td>R$5</td>
    </tr>
  </tbody>
</table>

5
  • 1
    Não é o tooltip que deve ter 30 caracteres ou 20, mas o que está sendo mostrado na <td>. O tooltip deve mostrar todo o conteúdo que vem do banco de dados.
    – pnet
    14/12/2015 às 12:24
  • @pnet agora faz todo o sentido para min, reeditando. 14/12/2015 às 12:26
  • Não funcionou o tooltip. No IE ele mostra e logo desaparece, o que eu quero é um tooltip que enquanto o mouse estiver sobre ele, ele não desapareça. Tentei vários exemplos, funciona numa table comum, mas na minha table, que é montada por javascript, não funciona. Vou postar o código completo dela e pode ser que alguém me ajude. Deixa eu explicar bem. Esses exemplos que eu tenho pego na internet, até funciona numa table comum, mas com a minha table não funciona.
    – pnet
    14/12/2015 às 12:26
  • @pnet entendi, reedite sua pergunta colocando estes detalhes e seus testes cross browsers que vai ajudar a ter uma resposta melhor. 14/12/2015 às 12:28
  • Fiz uma edição e postei o código da table, montada por javascript.
    – pnet
    14/12/2015 às 12:29

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .