2014-01-07 123 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>