开发者

Generating 2 dom elements in javascript

开发者 https://www.devze.com 2023-03-27 19:15 出处:网络
How do I debug problems like this. I have this code: var index = 0; $(\'#gen_field\').click(function() {

How do I debug problems like this. I have this code:

var index = 0;
$('#gen_field').click(function() {

    var next_row = $('<tr>').attr({
        'id': 'tbl_row' + index
    }).appendTo('#tbody_coll');

    var td1 = $('<td>').attr({
        'id': 'td_collector' + index
    }).appendTo(next_row);
    var td2 = $('<td>').attr({
        'id': 'td_rem' + index
    })开发者_StackOverflow中文版.appendTo(next_row);

    var collector = $('<input>').attr({
        'type': 'text',
        'name': 'collector[]'
    }).appendTo(td1).css('width', '200px');

    var rem_btn = $("<input>").attr({
        'type': 'button',
        'id': index,
        'name': 'rem',
        'class': 'rem',
        'value': 'del'
    }).appendTo(td2).addClass('span-2');

    console.log(index);
    index++;
});

This is supposed to generate only 1 field at a time. But its generating 2 of the same fields at once. Console.log is also showing 2 zeroes, then 2 ones when I click on the button that generates the fields. But I couldn't get any further into debugging this problem using firebug. Can you tell me what's wrong with my code?


If this code got executed more than once, then two identical click handlers will get attached, and each will run when the #gen_field is clicked.

BTW, if you're going to pass an HTML fragment to jQuery anyway to create a tag, why not specify the attributes at the same time in HTML instead of using .attr()?

0

精彩评论

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

关注公众号