2014-01-07 117 views
0

我有这个代码,但img.onclick不能正常工作,无法弄清楚是什么原因。有人能给我一些建议吗?由于为什么img.onclick无法正常工作?

var img = document.createElement('img'); 
img.src = "images/tv.jpg"; 
img.width = "280"; 
img.height = "200"; 
img.onclick = function() { 
    window.location.href = "~/HEMS/EditDevice.cshtml"; 
} 

............... 

cell.appendChild(img);` 
+0

的'href'你'试图设置给出了本地文件的印象(推测在Linux/Unix上?),尝试使用'file:///'协议的绝对路径(如果您选择省略localhost,则使用三斜杠符号主持人-name来自URL) –

+0

鉴于文件扩展名我怀疑它是一个.NET相对位置 – Liath

回答

1

Here is working demo

它可以正常使用,您需要确保URL是改变网页位置正确:

var img = document.createElement('img'); 
img.src = "images/tv.jpg"; 
img.width = "280"; 
img.alt='Url not exist'; 
img.height = "200"; 
img.onclick = function() { 
    alert('1'); 
} 

document.getElementById("cell").appendChild(img); 
0

尝试

var img = document.createElement('img'); 
    img.src = "images/tv.jpg"; 
    img.width = "280"; 
    img.height = "200"; 
    img.onClick = function() { 
     window.location.href = "~/HEMS/EditDevice.cshtml"; 
    } 

    ............... 

    cell.appendChild(img); 

我相信它的onclick没有的onclick。

此外,您重定向到的URL似乎是使用tilda表示法的MVC页面,因为这是服务器端概念,所以这不适用于JavaScript。

+0

好吧,让我试试 – user3156931

+0

我指的是外壳 - js区分大小写 – Liath

+0

sry说,它仍然不工作〜 – user3156931

0

试试这个:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
<title></title> 
<meta name="description" content=""> 
<meta name="viewport" content="width=device-width"> 
</head> 
<body> 

<div id="content"> 
    content 
</div> 


<script type="application/javascript"> 
var img = document.createElement('img'); 
    img.src = "grid.png"; 
    img.width = "280"; 
    img.height = "200"; 
    img.onclick = function() { 
     window.location.href = "~/HEMS/EditDevice.cshtml"; 
    }  
var cnt = document.getElementById('content'); 
    cnt.appendChild(img); 
</script> 

</body> 
</html>