문제

I am encountering a problem assigning classes and hidding and showing td's. Here is my HTML:

<table id="fundTable">
    <tr> 
         <td class="rentability"> <span class="someClass"> 0.12 </span> </td>
         <td class="absoluteResult">0.66</td>
    </tr>
    <tr> 
         <td class="rentability"> <span class="someClass"> -0.24  </span> </td>
         <td class="absoluteResult">-.45</td>
    </tr>
</table>

Here is my Javascript (onchange):

$('#fundTable tr').each(function() {
    formatedAbsoluteResult = 'SOME NUMBER'
    $(this).find('td[class=absoluteResult]').fadeOut(100).html(formatedAbsoluteResult).fadeIn(100)
    if (formatedAbsoluteResult < 0)
        $(this).find('td[class=absoluteResult]').removeClass('green').addClass('red')
    else 
        $(this).find('td[class=absoluteResult]').removeClass('red').addClass('green')
}

The idea is to display the number in green if it is positive, by assigning the appropriate class. In red otherwise. This code works perfectly when I run it once on page load. Then, the td's that have an assigned class (either red or green) are not updated anymore (onchange), whereas the others are on:

$(this).find('td[class=absoluteResult]').fadeOut(100).html(formatedAbsoluteResult).fadeIn(100)

I do not understand this behaviour. Any help greatly appreciated.

도움이 되었습니까?

해결책

I think a slight adjustment of your overall design of this block will help.

This seems to do what you are trying to accomplish (live demo at jsFiddle). Don't forget to change the parts where I improvised:

    $("#testing").keyup(function() {
    $("#fundTable tr").each(function() {
       formattedAbsoluteResult = 
        $(this).find("td.absoluteResult").fadeOut(100, function () {
            if (formattedAbsoluteResult < 0)
            {
                $("#fundTable tr").find("td.absoluteResult").removeClass("green").addClass("red");
            }
            else
            {
                $("#fundTable tr").find("td.absoluteResult").removeClass("red").addClass("green");
            }
        }).html(formattedAbsoluteResult).fadeIn(100);
    });
});

Notice the callback function used, also "keyup" instead of "onchange", but you can use whatever you need. Hope this helps.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top