[英]img onclick call to JavaScript function
我試圖制作一個img,當它被點擊時,調用一個JavaScript函數。
我在網上搜索過但沒有找到任何實際可行的東西(因為我犯了一個錯誤,所以)。
此代碼用於將JavaScript變量傳遞給ac#application。
誰能告訴我我做錯了什么?
<script type="text/javascript">
function exportToForm(a,b,c,d,e) {
window.external.values(a.value, b.value, c.value, d.value, e.value);
}
</script>
</head>
<body>
<img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
<button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>
</body>
這應該工作(有或沒有'javascript:'部分):
<img onclick="javascript:exportToForm('1.6','55','10','50','1')" src="China-Flag-256.png" />
<script>
function exportToForm(a, b, c, d, e) {
alert(a, b);
}
</script>
您可能應該使用更不引人注目的方法。 這是好處
- 從網頁的結構/內容和表示中分離功能(“行為層”)
- 避免傳統JavaScript編程問題的最佳實踐(例如瀏覽器不一致和缺乏可伸縮性)
- 逐步增強,以支持可能不支持高級JavaScript功能的用戶代理
你的JavaScript
function exportToForm(a, b, c, d, e) {
console.log(a, b, c, d, e);
}
var images = document.getElementsByTagName("img");
for (var i=0, len=images.length, img; i<len; i++) {
img = images[i];
img.addEventListener("click", function() {
var a = img.getAttribute("data-a"),
b = img.getAttribute("data-b"),
c = img.getAttribute("data-c"),
d = img.getAttribute("data-d"),
e = img.getAttribute("data-e");
exportToForm(a, b, c, d, e);
});
}
您的圖片將如下所示
<img data-a="1" data-b="2" data-c="3" data-d="4" data-e="5" src="image.jpg">
把javascript部分和結束放在結束</body>
然后它應該工作。
<img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
<button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>
<script type="text/javascript">
function exportToForm(a,b,c,d,e) {
alert(a + b);
window.external.values(a.value, b.value, c.value, d.value, e.value);
}
</script>
那么你的onclick功能可以很好地完成你的這一行
window.external.values(a.value, b.value, c.value, d.value, e.value);
window.external是對象,沒有方法名稱值
<html>
<head>
<script type="text/javascript">
function exportToForm(a,b,c,d,e) {
// window.external.values(a.value, b.value, c.value, d.value, e.value);
//use alert to check its working
alert("HELLO");
}
</script>
</head>
<body>
<img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
<button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>
</body>
</html>
回應maček的良好解決方案。 解決方案對我不起作用。 我必須將數據的值綁定到導出函數。 這個解決方案對我有用:
function exportToForm(a, b, c, d, e) {
console.log(a, b, c, d, e);
}
var images = document.getElementsByTagName("img");
for (var i=0, len=images.length, img; i<len; i++) {
var img = images[i];
var boundExportToForm = exportToForm.bind(undefined,
img.getAttribute("data-a"),
img.getAttribute("data-b"),
img.getAttribute("data-c"),
img.getAttribute("data-d"),
img.getAttribute("data-e"))
img.addEventListener("click", boundExportToForm);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.