Изменение ячейки в html-таблице с простого текста на гиперссылку

#javascript #java #html #json

#javascript #java #HTML #json

Вопрос:

Я работаю над простым самостоятельным проектом, чтобы представить массив JSON в таблице. Эта таблица содержит: «имя процесса», «имя файла», «ссылка» и логический флаг с именем «передается». Основная проблема заключается в том, что я хотел бы изменить ячейки под ссылкой на гиперссылку, которую можно нажать и привести меня к другому пути.

Текущее состояние таблицы:

введите описание изображения здесь

Прикрепление HTML и JS-кода:

 <!DOCTYPE html>
<html>
<head>
    <title>test report</title>
    <style>
        th, td, p, input, h3 {
            font:15px 'Segoe UI';
        }
        table, th, td {
            border: solid 1px #ddd;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
        th {
            font-weight:bold;
        }
    </style>
</head>
<body>
    <p id='showData'></p>
    
</body>

<script>

tableFromJson();

    function tableFromJson() {
        // the json data. (you can change the values for output.)
        var myFiles = 
[
  {
    "process_name":"Process1",
    "file_name":"file1",
    "link":"/compared_text/Process1/file1.html",
    is_passed:true
  },
  {
    "process_name":"Process1",
    "file_name":"file2",
    "link":"/compared_text/Process1/file2.html",
    is_passed:true
  },
  {
    "process_name":"Process2",
    "file_name":"file1",
    "link":"/compared_text/Process2/file1.html",
    is_passed:true
  },
  {
    "process_name":"Process2",
    "file_name":"file2",
    "link":"/compared_text/Process2/file2.html",
    is_passed:true
  }
]

        var col = [];
        for (var i = 0; i < myFiles.length; i  ) {
            for (var key in myFiles[i]) {
                if (col.indexOf(key) === -1) {
                    col.push(key);
                }
            }
        }

        // Create a table.
        var table = document.createElement("table");

        // Create table header row using the extracted headers above.
        var tr = table.insertRow(-1);                   // table row.

        for (var i = 0; i < col.length; i  ) {
            var th = document.createElement("th");      // table header.
            th.innerHTML = col[i];
            tr.appendChild(th);
        }

        // add json data to the table as rows.
        for (var i = 0; i < myFiles.length; i  ) {

            tr = table.insertRow(-1);

            for (var j = 0; j < col.length; j  ) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = myFiles[i][col[j]];
            }
        }

        // Now, add the newly created table with json data, to a container.
        var divShowData = document.getElementById('showData');
        divShowData.innerHTML = "";
        divShowData.appendChild(table);
        
    }
    
    

</script>
</html>
  

Ответ №1:

Вы можете создавать ссылки таким образом

Я думаю, вам следует заменить tabCell.innerHTML = myFiles[i][col[j]]; на что-то подобное (когда это ссылка, которую вы собираетесь добавить):

 var a = document.createElement('a');
a.title = "my title text";
a.href = "http://example.com";
tabCell.appencChild(a);
  

Ответ №2:

Вы можете попробовать что-то вроде этого:

 for (var i = 0; i < myFiles.length; i  ) {
    tr = table.insertRow(-1);
    for (var j = 0; j < col.length; j  ) {
        var tabCell = tr.insertCell(-1);
        if (j === 2) {
            tabCell.innerHTML = `<a href="${myFiles[i][col[j]]}">${myFiles[i][col[j]]}</a>"`;
        } else {
            tabCell.innerHTML = myFiles[i][col[j]];
        }
    }
}
  

Он проверяет, является ли это ссылкой (в вашем случае ссылки J = 2), и вставляет в <a href="></a>

Ответ №3:

Вы можете изменить часть добавления данных следующим образом.

 if(new String(myFiles[i][col[j]]).indexOf('.html')>-1){
                tabCell.innerHTML = '<a href="'   myFiles[i][col[j]]   '">Click For Details</a>';
            }else{
                tabCell.innerHTML = myFiles[i][col[j]];
            }
  

Ответ №4:

Проверьте, находится ли записываемая ячейка в link столбце, и соответствующим образом измените передаваемое значение innerHTML .

 for (var j = 0; j < col.length; j  ) {
    var tabCell = tr.insertCell(-1);
    let content = myFiles[i][col[j]];
    tabCell.innerHTML = col[j] === 'link' ? 
        `<a href="${content}">${content}</a>` : content;
}
  

 <!DOCTYPE html>
<html>
<head>
    <title>test report</title>
    <style>
        th, td, p, input, h3 {
            font:15px 'Segoe UI';
        }
        table, th, td {
            border: solid 1px #ddd;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
        th {
            font-weight:bold;
        }
    </style>
</head>
<body>
    <p id='showData'></p>
    
</body>

<script>

tableFromJson();

    function tableFromJson() {
        // the json data. (you can change the values for output.)
        var myFiles = 
[
  {
    "process_name":"Process1",
    "file_name":"file1",
    "link":"/compared_text/Process1/file1.html",
    is_passed:true
  },
  {
    "process_name":"Process1",
    "file_name":"file2",
    "link":"/compared_text/Process1/file2.html",
    is_passed:true
  },
  {
    "process_name":"Process2",
    "file_name":"file1",
    "link":"/compared_text/Process2/file1.html",
    is_passed:true
  },
  {
    "process_name":"Process2",
    "file_name":"file2",
    "link":"/compared_text/Process2/file2.html",
    is_passed:true
  }
]

        var col = [];
        for (var i = 0; i < myFiles.length; i  ) {
            for (var key in myFiles[i]) {
                if (col.indexOf(key) === -1) {
                    col.push(key);
                }
            }
        }

        // Create a table.
        var table = document.createElement("table");

        // Create table header row using the extracted headers above.
        var tr = table.insertRow(-1);                   // table row.

        for (var i = 0; i < col.length; i  ) {
            var th = document.createElement("th");      // table header.
            th.innerHTML = col[i];
            tr.appendChild(th);
        }

        // add json data to the table as rows.
        for (var i = 0; i < myFiles.length; i  ) {

            tr = table.insertRow(-1);
            
            for (var j = 0; j < col.length; j  ) {
                var tabCell = tr.insertCell(-1);
                let content = myFiles[i][col[j]];
                tabCell.innerHTML = col[j] === 'link' ? `<a href="${content}">${content}</a>` : content;
            }
        }

        // Now, add the newly created table with json data, to a container.
        var divShowData = document.getElementById('showData');
        divShowData.innerHTML = "";
        divShowData.appendChild(table);
        
    }
    
    

</script>
</html>  

Комментарии:

1. Рад помочь, если вы могли бы принять ответ, который был бы отличным.