在特定元素上执行javascript行[关闭]

问题描述 投票:-7回答:2

我有这个代码示例

<div id='1'>
<div class='2'>
<script type='text/javascript' src='..'</script>
</div>
</div>

我想要的是将脚本行放在正文的底部,并将第二个类作为目标,使其正常运行,就好像它在里面一样。我已经看到了他们成功实现的网站。

编辑上面的代码只是一个例子,而不是实际的代码。我通过在w3schools中查看DOM innerHTML找到了解决方案。

javascript
2个回答
3
投票

听起来你正在谈论一个脚本,它在遇到document.write标签时使用script同步输出内容,例如:

.foo {
  border: 1px solid black;
}
<div class="foo">
<script>document.write("I'm in the div");</script>
</div>

这样做的现代方法是随后操纵DOM

  1. 选择目标元素,和
  2. 插入/删除/修改内容

我将使用id="the-div"而不是id="1"class="the-class"而不是class="2",因为虽然可以用CSS选择器选择你的版本,但它不必要地笨拙(因为它们以数字开头)。

这是选择元素并修改其内容的示例:

document.querySelector("#the-div .the-class").innerHTML = "I'm in the div";
.the-class {
  border: 1px solid black;
}
<div id='the-div'>
<div class='the-class'>
</div>
</div>

你通过the DOM操作元素(直接,或者使用库和/或框架,如jQuery,Knockout,React,Vue.js等)。


1
投票

包含函数或类声明未包含的“松散”JavaScript行的<script>元素的位置将导致这些行在DOM解析遇到它们的位置执行。这种线性脚本在很多年前就已经使用过,通常用于使用document.write()在文档的正确位置生成动态内容。

这种类型的脚本本身适用于散布在整个文档中的多个脚本,这使得难以维护和调试页面。相反,如果您希望代码对文档进行更改,通常最好在文档的元素完全解析后执行脚本。

有两种方法可以让您的脚本在此时运行。

  1. 将您的脚本放在关闭的body标记之前:

<!doctype html>
<html>
<head>
  <title></title>
</head>
<body>
  <div id='1'>
    <!-- Class names cannot start with a number. -->
    <div class='two'></div>
  </div>


  <!-- The simplest way to ensure your script runs after all the HTML content
       has been parsed is to place the script just before the closing body tag. -->
  <script>
    // Just have the script locate the element(s) you want to work with:
    var nestedDiv = document.querySelector(".two"); // Finds first element that has the "two" class
    nestedDiv.textContent = "I've been added dynamically!"; // Update the text of the element
  </script>
</body>
</html>

2.当构成文档的所有元素都已解析到内存中时,浏览器将触发DOMContentLoaded事件,并且您可以设置在该事件(或其他事件)发生时自动调用的函数。

<!doctype html>
<html>
<head>
  <title></title>
  
  <!-- If using events, the location of the script doesn't matter because the
       script's code won't execute until the event it's tied to occurs. -->
  <script>
    // Set up a function to be called when the right event occurs
    window.addEventListener("DOMContentLoaded", function(){
      // Just have the script locate the element(s) you want to work with:
      var nestedDiv = document.querySelector(".two"); // Finds first element that has the "two" class
      nestedDiv.textContent = "I've been added dynamically!";
    });
  </script>
</head>
<body>
  <div id='1'>
    <!-- Class names cannot start with a number. -->
    <div class='two'></div>
  </div>
</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.