2017-07-18 129 views
0

的onclick功能無法在這種情況下工作:的onclick功能img標籤不工作

HTML

<img src="http://www.simplypo.ayz.pl/wp-content/uploads/2017/07/krakow- 
3.png" id="gabi" style="text-align: justify;" onClick="myFunction()" /> 

<p id="demo">Hi!</p> 

JS

function myFunction() { 
var str = document.getElementById("demo").innerHTML; 
var res = str.replace("Hi", "Hello"); 
document.getElementById("demo").innerHTML = res; 
} 

https://jsfiddle.net/kkdrrmhd/2/

+1

這是因爲您已將代碼附加在'onLoad'函數上,單擊javascript面板中的cog以查看我的意思[示例](https://jsfiddle.net/GMan134/d66j01jn/)。可以將它添加到頭部/主體或執行'window.myFunction = function etc' – George

回答

1

試試這個

<img src="http://www.simplypo.ayz.pl/wp-content/uploads/2017/07/krakow-3.png" id="gabi" style="text-align: justify;" onClick="myFunction('<h2>Gabriela</h2> tomatoes.121')" /> 
<div id="text-display">dsadasd 
</div> 
<p id="demo">Visit Microsoft!</p> 

<script> 
function myFunction(sample) { 
    var str = document.getElementById("demo").innerHTML; 
    var res = str.replace("Microsoft", "W3Schools"); 
    document.getElementById("demo").innerHTML = res; 
} 
</script> 

Fiddle here

1

這是因爲你的代碼中缺省的jsfiddle包裹在window.onload功能。要改變這種狀況,點擊JavaScript設置圖標,將其更改爲「無包裝」的一個選項

enter image description here

1

我建議使用addEventListener而非內聯事件監聽器:

function replaceContents() { 
 
    var str = document.getElementById("demo").innerHTML; 
 
    var res = str.replace("Hi", "Hello"); 
 
    document.getElementById("demo").innerHTML = res; 
 
} 
 

 
document.getElementById('gabi').addEventListener('click', replaceContents);
<img src="http://www.simplypo.ayz.pl/wp-content/uploads/2017/07/krakow-3.png" id="gabi" style="text-align: justify;" /> 
 

 
<p id="demo">Hi!</p>