无法获得jquery If-Else正常运行

时间:2012-02-22 20:38:40

标签: javascript jquery

我可能已经长时间盯着这个了,而且我写的功能并不是那么复杂,但无论出于什么原因,我都无法让它正常运行。 h1标签应该更改,但我的if-else似乎没有根据“page_layout”变量运行。我的代码低于......任何想法?

<script>
    $(document).ready(
     function() {
         //Set text for H1 tags here
         var title = "Test title";

         //Set main-image layout here (1,2,3,4)
         var page_layout = "1";

         //If page_layout = 4, then set connected-image for top
         var connected_image = "images/connected-image.jpg";

         //Image for main-image area
         var main_image = "images/main-image.jpg";

         //Set main-image text here
         var main_image_text = "See how this works.";

         //Set main-image-text-url location
         var main_image_text_url = "http://www.example.com";

         //Do not touch this code
        $('h1').html(title);

        if (page_layout == "1"){
            $.('#main-image').css('background-image', main_image);
            $.('#main-image').css('background-position', 'top right');
            $.('#main-image').css('background-repeat','no-repeat');
            $.('#main-image').addClass('padding-21');
            $.('#main-image').html(main_image_text);
            $.('#main-image').append('<br><a href="' + main_image_text_url + '">tell me more</a>');
        }else if (page_layout == "2"){
            $.('#middle').css('font-size','15px');
            $.('#main-image').addClass('padding-21');
            $.('#main-image').html(main_image_text);
            $.('#main-image').append('<br><a href="' + main_image_text_url + '">tell me more</a>');
        }else if (page_layout == "3"){
            $.('#main-image').css('background-image', main_image);
            $.('#main-image').css('background-position', 'top left');
            $.('#main-image').css('background-repeat','no-repeat');
            $.('#main-image').addClass('padding-491');
            $.('#main-image').html(main_image_text);
            $.('#main-image').append('<br><a href="' + main_image_text_url + '">tell me more</a>');
        }else if (page_layout == "4"){
            $.('connected-image').css('background-image', connected_image );
            $.('connected-image').css('background-position', 'top right');
            $.('connected-image').css('background-repeat','no-repeat');
        }else{
            //Nothing
        }
     }
    )
</script>

3 个答案:

答案 0 :(得分:2)

对于初学者,你应该在javascript控制台中看到一些语法错误。您需要将选择器从$.('selector')更改为$('selector')(在.之后删除$

此外,$('connected-image')应该使用类选择器$('.connected-image')

答案 1 :(得分:2)

可能还有其他问题,因为你不清楚你所看到的行为是什么,但你不应该在$和开放的parens之间需要一段时间。

$('connected-image').css('background-repeat','no-repeat');

$.('connected-image').css('background-repeat','no-repeat');

答案 2 :(得分:0)

在每个if-else块中,添加:

console.log("This is case 1");

// ... do this inside each if-else {...}

console.log("This is case 4");

然后在打开firebug控制台的情况下重新加载页面,并检查块是否正在执行。如果是,那么你知道你的if-else条件是否正常工作,并且if-else块中的语句必须是问题。