在Jquery中单击时更改变量的值

时间:2012-11-24 21:08:00

标签: javascript jquery html html5

单击txtAnswerB div时,我无法更改选项变量的值,这是我的代码:

function checkAnswer(){
    var choice;

    $("#txtAnswerB").click(function() {
        choice = Option2;
        $(this).css("background-color","#fff000");
    });
}

ps:option2是一个全局变量

2 个答案:

答案 0 :(得分:0)

应该是这样的

    <script type="text/javascript">
        var choice;
        var Option2 = /*somenthing*/;

        $(function(){
        $("#txtAnswerB").bind('click',function(){
             checkAnswer($(this));
           });
        });

        function checkAnswer(_element){
        choice = Option2;
        $(_element).css("background-color","#fff000");
        alert(choice);

        }
    </script>

答案 1 :(得分:0)

您需要调用函数checkAnswer();才能初始化click()个事件...

示例:

HTML:

<div id="answerB" class="answer"> <div id="txtAnswerB" class="txtAnswer">Quest</div> </div>​

jQuery的:

checkAnswer();
function checkAnswer(){
var choice;
    $("#txtAnswerB").click(function() {
        choice = Option2;
        $(this).css("background-color","red");
    });
}​

查看实时DEMO