简体   繁体   中英

How to call javascript object method from within HTML

I have the following class:

export default class Cursor {
    currentMode = modes.highlight
    //methods to modify currentMode
    toggleSelector = () => {
        this.currentMode = modes.selector
    }

which I then import and instantiate in my Index.js file:

import Cursor from './state.js'
const cursor = new Cursor(null)

I then load the index.js into my index.html file via:

<script type="module"src="./js/index.js"></script>

But when i try to use the object method as seen below:

<li><a class="btn-floating green" onClick='cursor.toggleSelector()'><i class="material-icons">done</i></a></li>

I have the following error:

cursor not defined

Is there a way to fix this?

Edit:

I have now done this as recommended but still does not work:

<script type="module" src="./js/index.js">import {cursor} from "./js/index.js";</script>

But still having this:

(index):27 Uncaught ReferenceError: cursor is not defined
at HTMLAnchorElement.onclick ((index):27)

When you try to call onClick='cursor.toggleSelector()', cursor object would be needed to be present in scope of the Window object.
The scope of module where cursor is defined is different.

try something like this in the index.js, it should work.
Basically, it is assigning cursor to the Window object, which allows to call from the HTMLAnchor element.

import Cursor from './state.js'
const cursor = new Cursor(null);
window.cursor = cursor;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM