开发者

Help optimizing and writing a global jQuery function

开发者 https://www.devze.com 2023-02-21 00:49 出处:网络
I am going to have a page with a list of 10 questions. Each row is a question and each question has 4 radio buttons (horizontal unordered list using background images)

I am going to have a page with a list of 10 questions.

Each row is a question and each question has 4 radio buttons (horizontal unordered list using background images)

When I click a radio button in the first question, I clear all instances of the "checked" class and then add the "checked" class to the one I clicked. However, the buttons I click in question 1 cannot interfere with the buttons from question 2. So I am having a hard time to find a way to make this a global function that runs whenever I click ANY of the li items.

Here is my code:

EDIT: Added my code to jsfiddle.net - http://jsfiddle.net/bnA4g/3/ --Updated Link

li {
    list-style-type:none;
    list-style:none;
    display:inline-block;
    white-space:nowrap;
}

.horiz {
    background:url(blankRadio.png) no-repeat center center;
    width:58px;
    height:58px;
}

.checked {
  开发者_C百科  background:url(checkedBtn.png) no-repeat center center;
    width:58px;
    height:58px;
}

$(function () {
    var row1 = $('div#row1 ul > li');
    var row2 = $('div#row2 ul > li');


        $("ul#row1Btns li").click(function () {
            $(row1).removeClass('checked');
            $(this).addClass('checked');
            console.log('checked');
        });

        $("ul#row2Btns li").click(function () {
            $(row2).removeClass('checked');
            $(this).addClass('checked');
            console.log('checked');
        });
});

    
        
        
        
        
    


    
        
        
        
        
    


You could write:

$("div ul > li").click(function () {
    $(this).siblings().removeClass('checked');
    $(this).addClass('checked');
    console.log('checked');
});

this should do what you intended.


I'd add a class to your rows and buttons, instead of addressing them by ID. Then, remove the checked class from all rows, and then add it to the one that was just checked.

<ul class="buttons" id="row1btns">
    <li>...</li>
</ul>

<ul class="questions" id="row1">
    <li>...</li>
</ul>

And your script:

$("ul.buttons li").click(function () {
  $("ul.buttons li").removeClass('checked');
  $(this).addClass('checked');
  console.log('checked');
});

Also a style note, you've assigned your row1 variable as such:

var row1 = $('div#row1 ul > li');

It's not necessary to use the $ function with it again as you did here:

$(row1).removeClass('checked');

It's sufficient to use

row1.removeClass('checked');
0

精彩评论

暂无评论...
验证码 换一张
取 消