开发者

How to change class only in specified area on JQuery?

I have a table with some td elements with the same class. But i want to change claas only in specified area .selected.

I make this:

<tr>
<td>--</td>
<td class="mcost"></td>
</tr>
<tr class="selected">
<td><input type="radio" name="work" onclick="selone('.selected','#sel1','m');" checked="checked" /></td>
<td id="sel1" c开发者_JAVA技巧lass="mcost"></td>
</tr>
<tr class="selected">
<td><input type="radio" name="work" onclick="selone('.selected','#sel2','m');" /></td>
<td id="sel2" class="mcost"></td>
</tr>
<tr>
<td>--</td>
<td class="mcost"></td>
</tr>

And try this:

function selone(g,f,n){
    $(g).each(function(){
        $('.'+n+'cost').removeClass().addClass(n+'cost_dis');
    });
    $(f).removeClass().addClass(n+'cost');
}

But it's change class to all mcost elements =( Not only in specified area. How to improve it?


in your .each, you requery the entire dom for .mcost cells. You need to do the following:

function selone(g,f,n){
    $(g).each(function(){
        $(this).find('.'+n+'cost').removeClass().addClass(n+'cost_dis');
    });
    $(f).removeClass().addClass(n+'cost');
}

This will only change the .mcost items inside of your $(g) element. This should work. Let me know.


 $(".selected td").each( function() { $(this).addClass("whatever"); } );


You could use a better, and unobtrusive approach:

  1. remove the onclick-events in the html.

  2. Use the script to this:

    $(function () { $(".selected :radio").click(function () { var selected = $(this).parents(".selected:first"); selected.removeClass().addClass('mcost_dis'); selected.find('.mcost').removeClass().addClass('mcost'); }); });

(However the last line doesn't add much)

The problem is in the part $('.'+n+'cost') this does not consider the context it is called in. It will allways select all .mcost elements in the page. if you change it to: $(this).find('.'+n+'cost') it will search only in the context of g. Do the same for f. However, it all depends on what g and f are. Using .selected in this case it should give you what you want.


I don't think you need the each loop at all if you change your selector a bit. Wouldn't this work:

function selone(g,f,n) {
   // find elements that already have the class, and change them
   $(g + " ." + n + 'cost').removeClass().addClass(n+'cost_dis');

   // add class to newly selected item
   $(f).removeClass().addClass(n + 'cost');
}

Assuming you call it with

selone('.selected','#sel1','m');

Then within the function $(g + " ." + n + 'cost') evaluates as $(".selected .mcost") - which means "find elements of class 'mcost' that are descendents of elements with class 'selected'".

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜