img 上的 onClick 有效,但即使在 JavaScript 中也无法动态附加相同内容,这是怎么回事?
onClick on img works but cannot dynamically attach the same even in JavaScript, what is wrong?
以下代码创建两个 <img>
对象,一个在 html 中静态定义,其中一个事件有效,另一个在 JavaScript 中定义,但无效。明明这可以在JavaScript中完成,那有什么问题呢?
<!DOCTYPE html>
<html>
<head>
<script>
function build() {
var img = document.createElement("img");
img.src = "cat.jpg";
img.onclick = "alert('yo')";
document.getElementById("quiz").appendChild(img);
return img;
}
</script>
</head>
<body onLoad="build()">
<div id="quiz">
<img src="trex.jpg" onClick="alert('hello')"></img>
</div>
</body>
</html>
问题是您将onclick 函数设置为字符串。当你在 HTML 中定义一个 onclick 参数时,你给它一个字符串,它可以包含 Javascript 代码。
当您处于 javascript 时,您必须定义一个函数,当您单击图像时将调用该函数。
您可以将参数传递给函数,这将是触发它的事件。在以下情况下,e
将是事件。
img.onclick = function (e){ alert(e); };
您可以在 W3C 阅读更多关于 javascript 编队的信息:http://www.w3schools.com/jsref/event_onclick.asp
var img = document.createElement("img");
img.src = "http://thecatapi.com/api/images/get?format=src&type=jpg&size=med";
img.onclick = function(e) {
alert(e);
};
document.body.appendChild(img);
<img onclick="alert('hello')" src="http://thecatapi.com/api/images/get?format=src&type=jpg&size=med" />
以下代码创建两个 <img>
对象,一个在 html 中静态定义,其中一个事件有效,另一个在 JavaScript 中定义,但无效。明明这可以在JavaScript中完成,那有什么问题呢?
<!DOCTYPE html>
<html>
<head>
<script>
function build() {
var img = document.createElement("img");
img.src = "cat.jpg";
img.onclick = "alert('yo')";
document.getElementById("quiz").appendChild(img);
return img;
}
</script>
</head>
<body onLoad="build()">
<div id="quiz">
<img src="trex.jpg" onClick="alert('hello')"></img>
</div>
</body>
</html>
问题是您将onclick 函数设置为字符串。当你在 HTML 中定义一个 onclick 参数时,你给它一个字符串,它可以包含 Javascript 代码。
当您处于 javascript 时,您必须定义一个函数,当您单击图像时将调用该函数。
您可以将参数传递给函数,这将是触发它的事件。在以下情况下,e
将是事件。
img.onclick = function (e){ alert(e); };
您可以在 W3C 阅读更多关于 javascript 编队的信息:http://www.w3schools.com/jsref/event_onclick.asp
var img = document.createElement("img");
img.src = "http://thecatapi.com/api/images/get?format=src&type=jpg&size=med";
img.onclick = function(e) {
alert(e);
};
document.body.appendChild(img);
<img onclick="alert('hello')" src="http://thecatapi.com/api/images/get?format=src&type=jpg&size=med" />