简体   繁体   中英

How can I change the inline javascript code to plain javascript code in the js file?

I am currently learning js and I'm making a chrome extension.
After finishing the tutorial, I want to add more features for the extension. And I did it!
You can see down below, I added buttons to delete the corresponding list.
What I added

However, when i deploy the extension, it couldn't work. And i found out that the problem is chrome extensions don't allow you to have inline JavaScript.
And i have no idea how to convert the code to plain js.

Here is my code which will render the list of items in the form of html.
<ul id="uls"></ul>

const ulElement = document.getElementById('uls');

function render(lists) {
    let listItems = ''
    for (let i = 0; i < lists.length; i++) {
        listItems += `
            <li>
                <button class='remove_data ${i}' onclick=getValue(this)>x</button>
                <a target='_blank' href='${lists[i]}'>
                    ${lists[i]}
                </a>
            </li>
        `
    }
    ulElement.innerHTML = listItems;
}

This is the js code that make the delete function.

const buttons = document.getElementsByClassName('remove_data');
let myWebsites = []

function getValue(element) {
    index = parseInt(element.className.split(' ')[1])
    deleteItem(index)

function deleteItem(index) {
    myWebsites.splice(index, 1)
    localStorage.setItem('myWebsites', JSON.stringify(myWebsites));
    render(myWebsites);
}

These code works fine in my live server. However, it couldn't work in chrome extension as there is onclick=getValue(this) in the html.
Can someone tell me how to convert it to js? Appreciate your help!

It's because you're using the onclick attribute, which uses inline JavaScript.

You can parse the HTML, then use addEventListener to add a click event listener to the button:

const ulElement = document.getElementById('uls');

function render(lists) {
    uiElement.innerHTML = '';
    for (let i = 0; i < lists.length; i++) {
            let li = document.createElement('li');
            li.innerHTML = `<li>
                <button class='remove_data ${i}'>x</button>
                <a target='_blank' href='${lists[i]}'>
                    ${lists[i]}
                </a>
            </li>`;
            li.querySelector('button').addEventListener('click', function(){
                getValue(this);
            }
        `
    }
}

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