用于.addEventListener
附加您的事件,并event.preventDefault();
防止在用户单击按钮时实际提交表单。此外,在注释 HTML 代码时,请使用 html 注释语法“ <!-- -->
”而不是“ //
”
html:
<div class="deo" id="a1">
<form id="formaA1" name="formaA1">
KOLIKO JE 3-1+5? <!-- It`s simple equation, it says: How much is 3-1+5? -->
<br/>
<input type="text" id="pitanjeA1" name="pitanjeA1" />
<br/>
<button id="submitButton">Odgovor</button>
</form>
</div>
JS:
/* http://dustindiaz.com/rock-solid-addevent */
function addEvent(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, fn, false);
EventCache.add(obj, type, fn);
}
else if (obj.attachEvent) {
obj["e" + type + fn] = fn;
obj[type + fn] = function() {
obj["e" + type + fn](window.event);
}
obj.attachEvent("on" + type, obj[type + fn]);
EventCache.add(obj, type, fn);
}
else {
obj["on" + type] = obj["e" + type + fn];
}
}
var EventCache = function() {
var listEvents = [];
return {
listEvents: listEvents,
add: function(node, sEventName, fHandler) {
listEvents.push(arguments);
},
flush: function() {
var i, item;
for (i = listEvents.length - 1; i >= 0; i = i - 1) {
item = listEvents[i];
if (item[0].removeEventListener) {
item[0].removeEventListener(item[1], item[2], item[3]);
};
if (item[1].substring(0, 2) != "on") {
item[1] = "on" + item[1];
};
if (item[0].detachEvent) {
item[0].detachEvent(item[1], item[2]);
};
item[0][item[1]] = null;
};
}
};
}();
addEvent(window, 'load', function() {
addEvent(document.getElementById("submitButton"), "click", function(event) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
if (parseInt(document.formaA1.pitanjeA1.value) == 7) {
document.getElementById("a1").innerHTML = "<img src='zmaj_01.jpg'>";
return true;
} else {
alert("Netacan odgovor. \nPokusajte ponovo.");
return false;
}
});
});
<a href="http://jsfiddle.net/ZrfAr/5/show/" rel="nofollow">现场演示 | 来源