全局变量更改后,函数仍然有效

时间:2015-12-13 16:59:23

标签: jquery html

好的我有代码:

$(document).ready(function(){
if(selected == 0){
    $(".color").mouseover(function(){
        var image = $(this).children('img').attr('src');
        $(this).children('img').css("border", "2px solid #000000");
        $("#itemMainImg").attr("src", image);
    });
    $(".color").mouseout(function(){
        $(this).children('img').css("border", "none");
    })
    $(".color").click(function(){
        var image = $(this).children('img').attr('src');
        console.log("worked");
        $("#itemMainImg").attr("src", image);
        $(this).children('img').css("border", "2px solid #000000");
        selected = 1;
        console.log(selected);
        colorSelected = $(this).children('img').attr('src');
    });
}
else{
    $(".color").click(function(){
        var image = $(this).children('img').attr('src');
        if(image == colorSelected){
            $("#itemMainImg").attr("src", image);
            if($(this).children('img').css("border") == "none"){
                $(this).children('img').css("border","2px solid #000000");
            }
            else{
                $(this).children('img').css("border", "none");
                selected = 0;
            }
        }
    });
}   
});

我有一个全局变量,var selected = 0;

和var colorSelected ="&#34 ;;

html看起来像这样:

<div id="itemHead">
<div id="itemMain">
    <h1 id="itemH1">Demo Item by Demo</h1>
    <img id="itemMainImg" src="photos/Carpets/ApolloBoxwood - Copy.jpg">
</div>
<div id="itemColors">
    <div>
        <p id="colorsP">Available Colours</p>
    </div>
    <div>
        <div class="color">
            <img class="colorImg" src="photos/Carpets/ApolloBoxwood - Copy.JPG" alt="Apollo Plus Boxwood">
            <p class="colorPara">Boxwood</p>
        </div>
        <div class="color">
            <img class="colorImg" src="photos/Carpets/ApolloCinderGrey - Copy.JPG" alt="Apollo Plus Cinder Grey">
            <p class="colorPara">Cinder Grey</p>
        </div>
        <div class="color">
            <img class="colorImg" src="photos/Carpets/ApolloCorkOak - Copy.JPG" alt="Apollo Plus Cork Oak">
            <p class="colorPara">Cork oak</p>
        </div>
    </div>      
</div>

由于某种原因,当我点击.color divs时,所选值被更改为1,但该函数仍然像值为0.因此在页面var selected设置为1,但是if的第一部分声明仍然有效。我不认为应该通过点击改变全局变量。

1 个答案:

答案 0 :(得分:1)

您正在根据selected的值绑定文档就绪的点击事件 - 只有代码中的第一个点击事件才会被绑定到元素,因为初始值为零。您需要将逻辑移入click函数,以便每次运行函数时都检查该值:

$(document).ready(function(){

    $(".color").click(function(){
       if(selected == 0){
          /* do something if value is zero */
       } else {
          /* do something if value is NOT zero */
       }
    });

});