1

I keep running up against this issue, which reflects my basic lack of understanding.

I want to collect all instances of a class, then be able to have a function which understands which element instance called it.

I created a Fiddle, http://jsfiddle.net/AKa4s/, which doesn't work, just to try to explain my question.

It's like this, I collect all the div elements & assign a function to it: $(".square").each(writeColorpanel);

Then in that function I need to call another function. The next function seems to have absolutely no idea who called. I need caller ID (joke).

The problem is that I end up running the same calculations for different divs, and repeating the function so that I can apply css to each of the divs based on the results.

4

2 に答える 2

1

あなたはそれをあまりにも複雑にしています。

jQuery(document).ready(function($) {


// run the function for every div
$(".square").each(function(i) {

    $('.output').eq(i).val(multiplyColor($(this).val()));
    //Show the output to the 1st/2nd/3rd output (that's where eq comes from
    //As for the value, I call a function and pass a parameter to do the calculations

    //Now if you want to call another function you need to pass the element itself as a parameter;
    alertMyId($(this));
});

function alertMyId(elem) {
   //elem has now all the same properties as if you were in the "each" function      
    alert(elem.attr('id'));

}

//Ideally if you just want to calculate something, you should just pass along the value you want to calculate
function multiplyColor(value) {
  var color = 3;
  return  value * color;
}

}); このフィドルをチェックしてください

また、同じ ID を持つ異なる html 要素を持つことはできません。代わりにクラスを使用してください。

于 2012-08-06T14:13:35.110 に答える
0

それはこのようなものですか:

$(function() {
    $(".square").each(function(i,e) {
        writeColorpanel(i,e);
    });

    function writeColorpanel (i, elem) {
       color=3;        
       onColorChange(elem, color);
    }

    function onColorChange(elem, color) {
       var m = elem.value
       var q = m*color;
       $('#output_'+elem.id).val(q);
    }
});

フィドル

于 2012-08-06T14:10:21.703 に答える