JavaScript event listener firing when declared, and never again
I have a unique little problem. I have to show and hide a container, when a specific radio button is selected. Unfortunately my event listeners a开发者_如何学运维re being fired when declared, and not when the event actually occurs. Has anyone else run in to this sort of issue?
<!DOCTYPE html>
<html>
<head><title>test</title></head>
<body>
<form name="form">
<input type="radio" name="r1" id="r1_yes" value="yes">
<input type="radio" name="r1" id="r1_no" value="no">
<div id="r1_comments" class="comments">Comments r1</div>
<br />
<input type="radio" name="r2" id="r2_yes" value="yes">
<input type="radio" name="r2" id="r2_no" value="no">
<div id="r2_comments" class="comments">Comments r2</div>
</form>
<script type="text/javascript">
function checkCommentTrigger(element, comments, trigger) {
if (element.value===trigger && element.checked) { comments.style.display="block"; }
else { comments.style.display="none"; }
}
function comments(fieldName, commentsID, triggerValue) {
var t_elements, t_comments, i;
t_elements = document.getElementsByName("fieldName");
t_comments = document.getElementById(commentsID);
t_comments.style.display="none";
for (i=0; i<t_elements.length; i++) {
if (t_elements[i].addEventListener){t_elements[i].addEventListener("click",checkCommentTrigger(this, t_comments, triggerValue),true);}
else {t_elements[i].addEvent('onclick',checkCommentTrigger(this,t_comments,triggerValue));}
}
}
comments("r1","r1_comments","no");
comments("r2","r2_comments","no");
</script>
</body>
</html>
You're calling the function in your "addEventListener" call. That is, in this code (broken into two lines):
if (t_elements[i].addEventListener){
t_elements[i].addEventListener("click",checkCommentTrigger(this, t_comments, triggerValue),true);}
you're calling the "checkCommentTrigger()" function. What you have to do is pass in a reference to a function, so something like this:
if (t_elements[i].addEventListener){
t_elements[i].addEventListener("click",function() { checkCommentTrigger(this, t_comments, triggerValue) },true);}
Same for the other branch of the "if":
else {
t_elements[i].attachEvent('onclick',function() { checkCommentTrigger(this,t_comments,triggerValue) });}
Also, you want "attachEvent()" for IE, not "addEvent()".
edit — looking at this again, there'll be a problem in that code if you use it as I wrote above. The problem will stem from the reference to this
in the function to use as an event handler. I think that you want the first argument to "checkCommentTrigger" to be the element to be checked. It might be simplest to set up a separate function:
function handlerFor(element, comments, value) {
return function() {
checkCommentTrigger(element, comments, value);
}
}
Then you can call that when you need an event handler function:
if (t_elements[i].addEventListener){
t_elements[i].addEventListener("click", handlerFor(t_elements[i], t_comments, triggerValue), true);
}
精彩评论