外部JavaScript可以从其他文件访问DOM元素吗? [英] Can external JavaScript access DOM elements from a different file?

查看:133
本文介绍了外部JavaScript可以从其他文件访问DOM元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近刚开始在Dreamweaver中工作。我想知道当您使用外部javascript文件时,是否必须传递html元素,或者js文件可以看到其ID?例如;

Just started working in Dreamweaver recently. I was wondering if when you are working with external javascript files, do you have to pass in html elements or can the js file see their id? For example;

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

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

然后在client.js文件中

And then in the client.js file

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

这首先没有用,我知道还有其他功能错误,但是主要是-client.js文件可以查看和使用 getElementById(submit) getElementById(otherelement)吗?

This isn't working in the first place and I understand that there are other errors, but mainly - can the client.js file see and use getElementById(submit) and getElementById(otherelement)?

推荐答案

我建议您不要使用内联JavaScript元素,而应采用其他方式。我建议使用 addEventListener() 绑定来自JavaScript的事件。

I would suggest shying away from using inline JavaScript elements, and doing things differently. I'd suggest using addEventListener() to bind events from JavaScript.

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

So, remove the onclick attribute, and just do:

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

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

We will be adding the event in JavaScript. For this to work, the script needs to be ran after the page (DOM) is loaded. You can use window.onload = function(){} to do this or you can load the script at the end of the page (before </body>).

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

Anyway, in your JavaScript, you want to use:

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可以从其他文件访问DOM元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆