开发者

Passing Variables To onChange Event with jQuery .change()

I'm writing a simple web application and have hit a stumbling block of sorts - I've already found a workaround, but I'd like to understand what I'm doing wrong having scoured the jQuery documentation.

开发者_运维知识库

I have a function, that when called from the page, inserts a table row:

var rowCount = 0;
function addRow(tbody){
    $("#"+tbody).append(
        $('<tr>').attr('id','row_'+rowCount).append(
            $('<td>').append('Content'),
            $('<td>').append($('<input>').addClass('text').attr('readOnly','readOnly')),
            $('<td>').append($('<input>').addClass('text').attr('readOnly','readOnly')),
            $('<td>').attr('id','barcode_cell'+rowCount),
            $('<td>').append($('<input>').addClass('text').addClass('quantity').attr('maxLength',3)),
            $('<td>').append($('<select>').change(function(){isMissing(this,rowCount)}))        
            )
    );
}

Where I am primarily concerned with the final <select> box and it's onChange event. My isMissing function:

function isMissing(elem, counter){
  alert(elem.value);
  alert(counter);
}

What happens is the selected value of the box alerts as expected, however, the row number always alerts the latest row, regardless of which row is calling it. Instead I want it to hold the value of the rowCount variable as it was when the row was introduced, not the latest value of the variable after I have added additional rows.

What am I doing wrong? How do I force the variable to remain static? I have to use a global variable as there is more than one function that adds rows to more than one table, this is the only way I can ensure each row in any table has a unique identifier.


This hapens because rowCount in global scope. You can make something like this inside you addRow method:

function addRow(tbody){
    var internalVariable = rowCount;
    $("#"+tbody).append(
        $('<tr>').attr('id','row_'+rowCount).append(
            $('<td>').append('Content'),
            $('<td>').append($('<input>').addClass('text').attr('readOnly','readOnly')),
            $('<td>').append($('<input>').addClass('text').attr('readOnly','readOnly')),
            $('<td>').attr('id','barcode_cell'+rowCount),
            $('<td>').append($('<input>').addClass('text').addClass('quantity').attr('maxLength',3)),
            $('<td>').append($('<select>').change(function(){isMissing(this,internalVariable)}))        
        )
);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜