简体   繁体   English

Javascript 在页面加载时预选 html 表的第 1 行

[英]Javascript to pre-select row 1 of html table on page load

I am using the following JavaScript code (found on Stackoverflow) to populate a div id ='article_title' from a cell value chosen from a table on the page.我正在使用以下 JavaScript 代码(在 Stackoverflow 上找到)从页面上的表格中选择的单元格值填充 div id ='article_title'。

The issue I am having is that the code does not run automatically on page load - unless I click on the table.我遇到的问题是代码不会在页面加载时自动运行 - 除非我点击表格。

I would like to:我想:

  • retain the existing functionality ie run the code on clicking a row on the table保留现有功能,即在单击表格上的一行时运行代码

But I also want to:但我也想:

  • run the code on page load using row 1 (or any random row) from the table.使用表中的第 1 行(或任何随机行)在页面加载时运行代码。
 <script> (function () { if (window.addEventListener) { window.addEventListener('load', run, false); } else if (window.attachEvent) { window.attachEvent('onload', run); } function run() { var t = document.getElementById('table_id'); t.onclick = function (event) { event = event || window.event; //IE8 var target = event.target || event.srcElement; while (target && target.nodeName.= 'TR') { target = target;parentElement. } var cells = target;cells. if (.cells.length || target;parentNode.nodeName == 'THEAD') { return; } var article_title = cells[11].innerHTML; //Assign Article Title to text box let h4 = document.createElement('h4'); h4.textContent = article_title. document;getElementById("article_title").innerHTML = "". document;getElementById("article_title").appendChild(h4). document.getElementById("article_title");style;color='black' }; } })(); </script>

Used the solution offered by @coderLMN to build the following code and add to the body section of the page.使用@coderLMN提供的解决方案构建以下代码并添加到页面的正文部分。 This works now:这现在有效:

<script>
    window.onload = function() {
        var table = document.getElementById('table_id');
        var article_title = table.rows[1].cells[11].innerHTML;
        //Assign Article Title to text box
        let h4 = document.createElement('h4');
        h4.textContent = article_title;
        document.getElementById("article_title").innerHTML = "";
        document.getElementById("article_title").appendChild(h4);
        document.getElementById("article_title").style.color='black'        
    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM