为什么img.onclick不起作用?

时间:2014-01-07 07:42:28

标签: javascript image 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);`

3 个答案:

答案 0 :(得分:1)

Here is working demo

它运行正常,您需要确保更改页面位置的网址正确无误:

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);

答案 1 :(得分: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中不起作用。

答案 2 :(得分: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>