从一个javascript文件中分别调用2个不同的函数

calling 2 different functions separately from one javascript file

本文关键字:2个 调用 函数 一个 文件 javascript      更新时间:2023-09-26

我有一个这样的脚本:

example.js :

function ex1(){document.write('example1');}
function ex2(){document.write('example2');}
ex1();
ex2();

我想使用ex1()ex2()example.js在我的html页面的不同地方,并以不同的样式它们。

那么我如何在我的html中分别调用这些ex1()ex2呢?这可能吗?如果可能,怎么做?

谢谢,

如果你从html中引用了这个文件,你可以毫无问题地调用这些函数。

你说的"造型"是什么意思?函数之间的区别是什么?

EDIT OP希望在每个函数中输出不同的样式:

function ex1(){document.write('<p class="classone">example1</p>');}<br>
function ex2(){document.write('<p class="classtwo">example1</p>'');}
之后,像这样修改你的CSS:
.classone{
   // styles for the first
}
.classtwo{
   // styles for the second
}

作为一种快速解释,document.write用括号" () "内的内容替换页面内容:

eg. document.write("hello world"); // Replaces everything with "hello world"

这是因为代码的document部分引用了页面主体中的所有内容(基本上是您看到的所有内容)。

要在页面的特定部分放置文本,必须首先引用想要放置文本的项/元素。您可以通过多种方式做到这一点,例如按元素引用(如@metal_fan的示例)、按类引用、按元素类型引用等。你也可以使用jQuery等框架来专门引用元素。

jQuery版本的@metal_fan的解决方案:

eg. jQuery("#myId").html("hello world"); // Replaces content of #myId element with "hello world"

正如@Kenneth所暗示的那样(尽管有点苛刻),要很好地使用它,您可能需要增加对javascript和HTML的理解。我可以建议你注册codingacademy.com turorials吗?它们非常全面,你可以获得积分,而且是免费的。

祝你好运!