簡體   English   中英

在HTML元素上嵌入onClick()函數不起作用

[英]Embedding an onClick() function on an HTML element doesn't work

chrome.storage.sync.get(['player_info'], (data) => {
    console.log('search')
    console.log(data)
    // data = list of possible players 
    let player_arr = data.player_info
    for (let i = 0; i < player_arr.length; i++) {
        document.getElementById("card-wrapper").innerHTML +=
            `<div onclick="alert('clicked')" class="player_option">
                <center>
                    <div class="card-img-small">
                        <a href="#">
                            <img id=\"player_img\" src="${player_arr[i].profile_img}" class="img-responsive">
                        </a>
                    </div>
                </center>
                <div class="card-body">
                    <div id="player-name" class="price-small">
                        ${player_arr[i].name}
                    </div>`
    }
})

我正在使用上面的代碼動態渲染某些項目。 div包裝器中,我添加了一個alert功能來檢查它是否有效,但是什么也沒發生。 我檢查了元素,它看起來像這樣:

<div onclick="alert('clicked')" class="player_option">
                <center>
                    <div class="card-img-small">
                        <a href="#">
                            <img id="player_img" src="https://fmdataba.com/images/p/4348.png" class="img-responsive">
                        </a>
                    </div>
                </center>
                <div class="card-body">
                    <div id="player-name" class="price-small">
                        Paul Pogba
                    </div></div></div>

該函數似乎已正確嵌入,但沒有發生alert 有什么幫助嗎?

編輯

實際上意識到我正在收到此錯誤: Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. 我正在構建Chrome擴展程序

在chrome應用和擴展程序中,內容安全策略不允許使用內聯JavaScript。 因此,您必須將JavaScript放在.js文件中,並將其包含在HTML中。

您必須改為使用js事件監聽器。 看一下這一點: 拒絕執行內聯事件處理程序,因為它違反了CSP。 (沙盒)

如果您仍想在onClick屬性中使用js,則還可以更改Content Security Policy 查看:“放松默認策略”下的“ 內容安全策略(CSP) ”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM