需要JS来修改脚本后面的元素

Need JS to modify the element following the script

本文关键字:元素 脚本 JS 修改 需要      更新时间:2023-09-26

我有一个报告创作工具,它允许我在包含数据的表之前在报告标题中添加描述性文本。该工具附带的示例展示了如何在各种特效的描述中包含Javascript。我想将表格中的某些单元格更改为指向其他报表的链接。下面是报告工具生成的HTML。

<div class="element-info">
  <div class="description">My Description</div>
  <div class="properties">
    <table>...</table>
  </div>
</div>

我已经尝试用以下内容替换"我的描述",但是(也许并不奇怪)它改变了表以外的东西。

<div>My Description
<script type="text/javascript">
// currentScript is supported in my version of Firefox.
var me = document.currentScript;
// go up two levels to get the enclosing div
var element_info = me.parentElement.parentElement;
// from there we want the properties div, then the table
var mytable = element_info.lastChild.firstChild;
mytable.style.color = "red";
</script>
</div>

我认为问题是当脚本运行时,下面的div中的HTML还没有被解析。Mozilla说,在没有src=属性的脚本中,defer属性将被忽略,我已经验证过它什么也不做。

虽然我的示例代码使用的是纯Javascript,但创作工具是基于jQuery的,因此如果需要,可以使用它的全部功能。

如果问题涉及html尚未被解析的事实,您可以立即获得对脚本的引用,但只有在加载文档后,才可以稍后使用它。它看起来像这样:

<div>My Description
    <script type="text/javascript">
    // Get the reference immediately...
    var script_of_interest = document.currentScript;
    // And only use it once everything is loaded:
    window.onload = function() {
        var element_info =  script_of_interest.parentElement.parentElement;
        var mytable = element_info.lastChild.firstChild;
        mytable.style.color = "red";
    };
    </script>
</div>

确保脚本操作的节点在执行前已加载,否则节点可能未定义或什么都没有。您可以尝试用$(document).ready(function(){ //your code }) .