JQuery, would like to update the onClick method of an element. jQuery's click() function isn't working with the syntax I am using -
still trying wrap head around jquery, in advance!
some context code. page allows user add questions dynamically, , each question can have associated answers entered in.
my thought process in order generate answer input boxes within correct question element need pass associated questionid addanswer function.
consequently, tried use attr() , update onclick attribute of add answer href googling led me try click() function.
the behavior getting whenever addquestion() run, appears addanswer() run, getting 2 alerts.
here's code.
<script> currentquestion = 1; function addquestion(){ $('#question0container').clone().attr('id','question'+currentquestion).appendto('#questionarea'); $('addanswer0').click(addanswer('0')); currentquestion++; } function addanswer(question){ alert(question); } </script> <div id="questionarea"> <div id="question0container" class="questioncontainer"> <textarea id="question0" name="question0"></textarea> <div id="answer0container"> <h2>answers</h2> <input type="text" id="0-answer1" /> </div> <p><a href="#" id="addanswer0" class="link-sm">add answer</a></p> </div> </div> <a href="#" onclick="addquestion();" id="addquestion" title="add question" class="link-sm" style="background-color:red;">add question</a>
easiest supply anonymous function (sometimes called lambda expression):
$('#addanswer0').click(function() { addanswer('0') });
the issue jquery event functions take functions arguments. is, jquery library organized around concept of higher-order functions. in javascript, if want call function foo, write foo(); whereas if want refer function, pass around, write foo. in case, however, want pass argument, want create new, anonymous function, calls other function, passing along argument.
Comments
Post a Comment