Using the same function with multiple buttons

2020-05-09 23:42发布

问题:

I have multiple buttons that should call the OpenPanel function but apparently chrome doesn't like it when I use inline event handlers. Are there any alternatives? Thanks!

Html:

<button id="showBg" class="panelB" onclick="OpenPanel(this)">Btn1</button>

<button id="showNews" class="panelB" onclick="OpenPanel(this)">Btn2</button>

JavaScript:

function OpenPanel(elem){
 alert (elem.id);
}

Chrome Error:

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.

回答1:

With jquery you could use the class as a selector and a click function...

HTML:

<button id="showBg" class="panelB">Btn1</button>
<button id="showNews" class="panelB">Btn2</button>

JQUERY:

$('button.panelB').click(function() {
    alert($(this).attr('id'));
});

If for some reason you need to call your OpenPanel function, that is expecting a DOM element instead of a jQuery object...

function OpenPanel(elem) {
    alert(elem.id);
}

$('button.panelB').click(function() {
    OpenPanel(this);
});

I hope it helps



回答2:

chrome doesn't like it when I use inline event handlers

Chrome has no problem with inline event handlers. The error message says that the problem is your Content Security Policy.

Either through HTTP headers or meta tags you have banned yourself from using inline event handlers.

This is probably for the best. Inline event handlers come with annoying gotchas.

Bind your event handlers with JavaScript instead.

function openPanelHanler(event) {
    OpenPanel(this);
}

var panels = document.querySelectorAll(".panelB");
for (var i = 0; i < panels.length; i++) {
    panels[i].addEventListener("click", openPanelHander);
}


回答3:

You can still use:

$(".panelB").click(function(){
   {...}
});

$(this) contains the current element that's been clicked.