繁体   English   中英

如何在 Express 和 Pug 中将 function 发送到 onclick 按钮?

[英]How do you send a function to an onclick button in Express and Pug?

我正在尝试发送一个 function,它可以分配给按钮元素的 onclick。

在我的一个页面上,我试图发送一个名为 showPopup 的 function 作为局部变量,然后我想将其分配给按钮 onclick..

服务器控制器.js

exports.get_server = (req, res, next) => {
    Server.findById(req.params.id).populate("channels").exec((err, server) => {
        if(err) next(err);

        let showPopup = () => {
            let c = document.querySelector("form.container-popup#add-channel");
            c.hidden = false;
        }

        res.render("server-page", {
            server: server, 
            user: res.locals.currentUser,
            showPopup: showPopup
        })
    })
};

频道侧栏.pug

div.secondary-side-bar
    div This is the channel side bar
    for channel in server.channels
        a(href=`/server/${server._id}/channel/${channel._id}`) #{channel.name}
        br
    button.add-channel(type="button" onclick=showPopup) Add Channel

    //- - showPopup() <-- runs my function when program runs

    form.container-popup#add-channel(method="POST" action=createChannelURL hidden=true)
        .div Create Channel
        label(for="name") Channel Name
        input(type="text" name="name" placeholder="Enter channel name here...")
        label(for="private") Private Channel?
        input(type="checkbox" value="private" name="private")

        button(type="submit") Submit
        
script.
    //- let addChannelButton = document.querySelector("button.add-channel")
    //- addChannelButton.onclick = showPopup;
    console.log("in pug script")

当我运行我的代码时,我收到一条错误消息:

拒绝执行内联事件处理程序,因为它违反了以下内容安全策略指令:“script-src-attr 'none'”。 启用内联执行需要“不安全内联”关键字、hash(“sha256-...”)或随机数(“nonce-...”)。 请注意,哈希不适用于事件处理程序、样式属性和 javascript:导航,除非存在“不安全哈希”关键字。

仅作记录,我还加上了这样的引号:

onclick="showPopup" 
onclick="showPopup()"  

我究竟做错了什么?

我也尝试过直接在 pug 页面脚本上添加 onclick function,但这似乎也没有运行。

你尝试构建一个 Chrome 扩展吗?
如果是这种情况,您应该阅读以下内容: https://developer.chrome.com/docs/apps/contentSecurityPolicy

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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