开发者

Jquery - How to create an object based on all the divs in a class?

On document ready, I am trying to create an object for all my div(s) in a class and assigned them based on the div's attribute 'id'. Here are my codes which doesn't work, I can't figure out.

<div class="supercolor" >                       
   <div class="colordiv" id="#111111" style="background-color:#111111;">&nbsp;</div>
   <div class="colordiv" id="#222222" style="background-color:#222222;" >&nbsp;</div>                
   <div class="colordiv" id="#333333" style="background-color:#333333;">&nbsp;</div>
</div>

And in my script section.

$(document).r开发者_运维知识库eady(function() {

   $('div.supercolor > div').each(function() {
      var color_object = { $(this).attr('id') : false }
   });
});

Thank you


$(function() {

    var divObjects = $("div.supercolor > div").map(function(val) {
        return new DivObject(this.id);
    }).get();

});

function DivObject(id) {
    this.id = id; 
    ...
}

This will take all your <div>'s and map them to div objects. You can pass in data from your individual <div> like the id and pass it to the constructor.

You have to call .get() to get out an array.

[Edit]

var testDiv = $.grep(divObjects, function(val) {
    val.id === "test"
})[0];

This code snippet may look more familiar though

var testDiv;
for (var i = 0, ii = divObjects.length; i < ii; i++) {
    var div = divObjects[i];
    if (div.id === "test") {
        testDiv = div;
        break;
    }
}


Unless there is a good reason for you to store an array of 'DivObjects', I would consider changing your approach.

On page load, attach click handlers to each colour div toggle a 'selected' class on the div (and remove it from others).

$("div.supercolor > div").click(function(){
    $(this).toggleClass('selected').siblings('.selected').removeClass('selected');
});

At any point you need to get the colour that has been selected (if any) select colour divs with 'selected' class, and pull it's id:

$("div.supercolor > div.selected").attr('id');

This may not be suitable in your situation, but it is simple and effective.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜