gpt4 book ai didi

javascript - 外部 JavaScript 可以访问不同文件中的 DOM 元素吗?

转载 作者:太空宇宙 更新时间:2023-11-04 16:11:44 24 4
gpt4 key购买 nike

最近刚开始使用 Dreamweaver。我想知道当您使用外部 javascript 文件时,是否必须传入 html 元素或者 js 文件是否可以看到它们的 id?例如;

<body>
<script src="client.js"></script>

<input type="submit" name="submit" id="submit" onclick="getValue()" value="Submit"></td>

然后在client.js文件中

function getValue() {
"use strict";
document.getElementById(submit).value = document.getElementById(otherelement).value;
}

这首先不起作用,我知道还有其他错误,但主要是 - client.js 文件可以看到并使用 getElementById(submit)getElementById(其他元素)?

最佳答案

我建议避免使用内联 JavaScript 元素,并以不同的方式做事。我建议使用 addEventListener() 从 JavaScript 绑定(bind)事件。

因此,删除 onclick属性,然后做:

<input type="submit" name="submit" id="submit" value="Submit">

我们将在 JavaScript 中添加事件。为此,脚本需要在页面 (DOM) 加载后 运行。您可以使用 window.onload = function(){}为此,您也可以在页面末尾加载脚本(在 </body> 之前)。

无论如何,在您的 JavaScript 中,您要使用:

document.getElementById("submit").addEventListener('click', function(event){
// NOTE: You are clicking a submit button. After this function runs,
// then the form will be submitted. If you want to *stop* that, you can
// use the following:
// event.preventDefault();

// In here `this` will be the element that was clicked, the submit button
this.value = document.getElementById('otherelement').value;
});

关于javascript - 外部 JavaScript 可以访问不同文件中的 DOM 元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34548969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com