我不确定这个脚本有什么问题。它“应该”有效。
HTML
<img src="https://placehold.it/350x150" alt="" onclick="goTo('img1');">
的Javascript
function goTo(img) {
if( img === 'img1' ) { window.open('https://www.google.com/','_blank'); }
else if( img === 'img2' ) { window.open('https://www.yahoo.com/','_blank'); }
etc...
else{ alert("This image is not recognized: " + img ); }
}
JsFiddle: https://jsfiddle.net/omarjuvera/xuzc70gn/2/
编辑:在网站上,我在.ready()中有javascript代码,如下所示:
$( document ).ready(function() {
function goTo(img) {
if( img === 'ivory' ) { window.open('https://www.indiegogo.com/project/preview/a0d4cff9','_blank'); }
else{ alert("This image is not recognized: " + img ); }
}
...more functions...
});
答案 0 :(得分:2)
您的goto函数未在全局范围内声明,因此无法找到。 尝试:
window.goTo = function (img) {
// your code
}
答案 1 :(得分:2)
只需将goTo
功能放在.ready()
事件之外,如下所示:
function goTo(img) {
if( img === 'ivory' ) { window.open('https://www.indiegogo.com/project/preview/a0d4cff9','_blank'); }
else{ alert("This image is not recognized: " + img ); }
}
$( document ).ready(function() {
...more functions...
});
答案 2 :(得分:1)
默认情况下,JsFiddle在页面加载时运行您的代码。换句话说,它将您的goTo()
函数包含在其他函数中,如下所示:
window.onload=function(){
function goTo(img) {
if( img === 'img1' ) {
window.open('https://www.google.com/','_blank');
}
else if( img === 'img2' ) {
window.open('https://www.yahoo.com/','_blank');
}
else {
alert("This image is not recognized: " + img );
}
}
}
这使得它无法访问,例如,HTML中的onclick
属性。
要解决此问题,您需要将“加载类型”设置更改为“No wrap-in&lt; body&gt;”: