Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

javascript - 动态调用javascript模块之外的函数(Dynamically calling a function outside of a javascript module)

I have the following javascript class in foo.js :

(我在foo.js有以下javascript类:)

export default class Foo {
  constructor(html) {
    this.html = html;
  }
}

which I'm importing and using as follows within select.js :

(我正在select.js导入和使用以下select.js :)

import Foo from './foo.js'

var html = ``;
let array = ['bar', 'baz', 'boom']; // etc. etc.
for (var i = 0; i < array.length; i++) {
  let element = array[i];
  html += `<a onclick=`select('${element}');`>element</a>`;
}
let foo = new Foo(html);
$(`select`).html(foo.html);

function select(name) {
  let foo = new Foo('foo'); // still module access ...
  console.log(`foo.html = ${foo.html}`);      
  console.log(`name = ${name}`);
}

The select element is defined in index.html as:

(select元素在index.html定义为:)

<div id="select"></div>
<script type="module" src="./select.js"></script>

where I have imported the select.js file as a module .

(我已将select.js文件导入为module 。)

However, I am getting the following error when I run this:

(但是,运行此命令时出现以下错误:)

(index):1 Uncaught ReferenceError: select is not defined at HTMLAnchorElement.onclick ((index):1)

((索引):1未捕获的ReferenceError:在HTMLAnchorElement.onclick中未定义选择((索引):1))

I need to have access to the class Foo so this javascript must be a module.

(我需要访问Foo类,因此此javascript必须是一个模块。)

Is there anyway to achieve having the scope of select within the index.html file?

(无论如何,要在index.html文件中实现select范围?)

Edit

(编辑)

A solution proposed in the comments could be to assign a unique handler to each id of the link elements after they have been embedded into the html, but this seems like a slightly verbose solution.

(评论中提出的解决方案可能是将链接元素的每个id嵌入到html后为其分配唯一的处理程序,但这似乎有点冗长的解决方案。)

  ask by alex_lewis translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...