例如:
<DIV>Here is some text..</DIV>
<DIV><IMG src="image1.png">one</DIV>
当用户点击图片(image1.png)时,我想将图片更改为image2.png?
如何使用普通的javascript进行此操作?
由于
答案 0 :(得分:2)
只需使用
<IMG src="image1.png" onclick='this.src="image2.png"'>
纯JS
document.getElementById('img').onclick=function() {
this.src='image2.png';
};
答案 1 :(得分:1)
<img ... onclick="this.src = 'image2.png'" />
在回复你的评论时,我没有一个纯粹的JS点击处理程序,但是对于jQuery,它看起来像这样:
$('img').click(function() {
$(this).attr('src', 'image2.png');
});
答案 2 :(得分:1)
<DIV>Here is some text..</DIV>
<DIV><IMG id="image1" src="image1.png">one</DIV>
<script type="text/javascript">
window.onload = (function(oldLoad) {
return function() {
oldLoad && oldLoad();
// wire up image event handler
document.getElementById("image1").onClick = function() {
this.src = "image2.png";
}
}
})(window.onload)
</script>
编辑 - 发表评论后:
有些时候很多人无法利用jQuery的强大功能。 OP希望在他的评论中知道oldLoad的目的是什么,我想提供一个详细的答案。
基本上我在这里写的是与jQuery的$(document).ready()类似的东西。以下是我将如何利用这个例子。
<script type="text/javascript">
var Core = {
windowLoadEvent: function(oldLoad, newLoad) {
return function() {
//check if the window.onload already has a function attached if so then execute
oldLoad && oldLoad();
//check if the newload has a function attached if so then execute
newLoad && newLoad();
},
myNewLoadEvent: function() {
document.getElementById("image1").onClick = function() {
this.src = "image2.png";
}
//wireup whatever else is needed.
}
}
window.onload = Core.windowLoadEvent(window.onload, Core.myNewLoadEvent)
</script>
答案 3 :(得分:0)
您也可以尝试此操作(Example)
<强> HTML:强>
<div id="images">
<div><IMG src="image1_url" />one</div>
</div>
<强> JS:强>
var images = document.getElementById('images');
images.onclick = function(e){
var event = e || window.event;
var target = event.target || event.srcElement;
target.src="image2_url";
};