开发者

jquery association array

开发者 https://www.devze.com 2023-01-25 00:16 出处:网络
Need a little help with what I\'m sure is fairly easy jquery I have the following repeating markup (several list items)

Need a little help with what I'm sure is fairly easy jquery

I have the following repeating markup (several list items)

<li>
<div class="answer">
<p><select class="dropdown">
..options..
</select></p>
</div>
<div class="commentBox">
..content开发者_JS百科..
</div>
</li>

Depending on the value of the selected option when the pages loads, the "commentBox" will be shown/hidden.

I have tried the following jquery

var dd = $('.dropdown');
var com = $('.commentBox');


dd.each(dd, function(n, val){
if($(this).val() == 'whatever'){
   com[n].setStyle('display', 'none');
}
});

I get an error "b.apply is not a function"

So in my head, how it should work - if it's the first select dropdown, show/hide the first "commentBox" div. If it's the second dropdown then show/hide the second "commentBox" div. And so on.

I think I have got in a mess trying various jquery techniques so I am sure there are dozens of possibilities here. Thanks


Your problem is that you're passing an extra (first) parameter to each.
each only takes the set as the first parameter when called statically.
In other words:

$.each(dd, function() { ... });

or

dd.each(function() { ... });

Note that you can make your code clearer by changing it to

$(this).closest('li').find('.commentBox').hide();


Try

var dd = $('.dropdown'),
    com = $('.commentBox');

dd.each(function(n, ele) {
    if( $(ele).val() == 'one') {
        com.eq(n).css('display', 'none');
    }
});

used .eq(n) instead of [n] the latter would yield the DOM node while mine yields a jQuery object on which you can call css() (as you see I switched from setStyle what is that function anyway to css()).


Using the enhancement suggested by Slakks you end up with this better readable piece of code

$('.dropdown').each(function(n, ele){
    var $ele = $(ele);
    if ($ele.val() == "one")
        $ele.closest('li').find('.commentBox').hide();
});


When calling .each() like that, you give it only one argument, the function.

dd.each(function(n, val){
    if($(this).val() == 'whatever'){
       com[n].setStyle('display', 'none');
    }
});

Or you can pass 2 arguments if you call jQuery.each like this:

$.each(dd, function(n, val){
    if($(this).val() == 'whatever'){
       com[n].setStyle('display', 'none');
    }
});

This second version is for iterating over any type of collection.

You were combining the two.


EDIT: I guess I better explain that setStyle is in the OP's code, and is not the immediate cause of the issue at hand.

I have no way of knowing if OP extended the DOM elements with additional methods. As such, I can only assume that the placement of such a method is correct.

0

精彩评论

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

关注公众号