最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery - binding click event to a variable - Stack Overflow

programmeradmin1浏览0评论

All,

I am really stuck/ confused at this point.

I have an array with 6 items in it. Each item in the array is dynamically filled with elements using jquery '.html' method. However, I cannot seem to be able to attach/ bind an event to this dynamically created variable.

As soon as the browser gets to the problem line (see the area labeled 'PROBLEM AREA'), I get a 'undefined' error, which is really confusing as all the previous code on the very same variable works just fine.

var eCreditSystem = document.getElementById("creditSystem");
var i = 0;
var eCreditT = new Array(6);                    // 6 members created which will be recycled

function createCreditTransaction ()                 // func called when a transaction occurs, at the mo, attached to onclick()
{
    if (i < 6)
    {
        eCreditT[i] = undefined;                    // to delete the existing data in the index of array
        addElements (i);
    } else
    if (i > 5 || eCreditT[i] != undefined)
    {
         ...
    }
}

function addElements (arrayIndex)                   // func called from within the 'createCreditTransaction()' func
{
    eCreditT[i] = $(document.createElement('div')).addClass("cCreditTransaction").appendTo(eCreditSystem);
    $(eCreditT[i]).attr ('id', ('trans' + i));
    $(eCreditT[i]).html ('<div class="cCreditContainer"><span class="cCreditsNo">-50</span>&nbsp;<img class="cCurrency" src="" alt="" /></div><span class="cCloseMsg">Click box to close.</span><div class="dots"></div><div class="dots"></div><div class="dots"></div>');
    creditTransactionSlideOut (eCreditT[i], 666);                   // calling slideOut animation
    console.log(eCreditT[i]);     // this confirms that the variable is not undefined

/* ***** THE PROBLEM AREA ***** */
    $(eCreditT[i]).on ('click', function ()                 // if user clicks on the transaction box
    {
        creditTransactionSlideBackIn (eCreditT[i], 150);                    // slide back in animation
    });
    return i++;
}

All,

I am really stuck/ confused at this point.

I have an array with 6 items in it. Each item in the array is dynamically filled with elements using jquery '.html' method. However, I cannot seem to be able to attach/ bind an event to this dynamically created variable.

As soon as the browser gets to the problem line (see the area labeled 'PROBLEM AREA'), I get a 'undefined' error, which is really confusing as all the previous code on the very same variable works just fine.

var eCreditSystem = document.getElementById("creditSystem");
var i = 0;
var eCreditT = new Array(6);                    // 6 members created which will be recycled

function createCreditTransaction ()                 // func called when a transaction occurs, at the mo, attached to onclick()
{
    if (i < 6)
    {
        eCreditT[i] = undefined;                    // to delete the existing data in the index of array
        addElements (i);
    } else
    if (i > 5 || eCreditT[i] != undefined)
    {
         ...
    }
}

function addElements (arrayIndex)                   // func called from within the 'createCreditTransaction()' func
{
    eCreditT[i] = $(document.createElement('div')).addClass("cCreditTransaction").appendTo(eCreditSystem);
    $(eCreditT[i]).attr ('id', ('trans' + i));
    $(eCreditT[i]).html ('<div class="cCreditContainer"><span class="cCreditsNo">-50</span>&nbsp;<img class="cCurrency" src="" alt="" /></div><span class="cCloseMsg">Click box to close.</span><div class="dots"></div><div class="dots"></div><div class="dots"></div>');
    creditTransactionSlideOut (eCreditT[i], 666);                   // calling slideOut animation
    console.log(eCreditT[i]);     // this confirms that the variable is not undefined

/* ***** THE PROBLEM AREA ***** */
    $(eCreditT[i]).on ('click', function ()                 // if user clicks on the transaction box
    {
        creditTransactionSlideBackIn (eCreditT[i], 150);                    // slide back in animation
    });
    return i++;
}
Share Improve this question asked Nov 26, 2011 at 8:28 KayoteKayote 15.7k26 gold badges96 silver badges152 bronze badges 6
  • I am wondering, could this have something to do with where the js file is loaded in the HTML doc from? I have the js file placed at the bottom of the body tag in HTML. – Kayote Commented Nov 26, 2011 at 9:11
  • Second theory is that is it possible that by the time it gets to 'binding' the event to the variable, the browser has already read & implemented the 'return i++', which would mean that at that moment, the 'eCreditT[i]' has a different value for 'i' than previously? – Kayote Commented Nov 26, 2011 at 9:30
  • Its worked! But I have no real idea of why it worked. When I mented the 'return i++' & ran the code, it worked. Now my problem is how do I implement the 'return i++' at the end of the function? – Kayote Commented Nov 26, 2011 at 9:35
  • 1 Try to add click event out of addElements() function and try once. – Kiran Commented Nov 26, 2011 at 9:40
  • @Kiran, thankyou, that DID work. I actually had tried this before as well but I must have done something wrong then as its clearly working now. A million thanks. – Kayote Commented Nov 26, 2011 at 9:53
 |  Show 1 more ment

5 Answers 5

Reset to default 2

Try this:

$(eCreditT[i]).bind('click', function() {
   creditTransactionSlideBackIn(eCreditT[i], 150);
});

Edit: use ++i instead of i++ like this:

return ++i;
/*
or
i += 1;
return i;
*/

retrurn ++i performs the increment first then return i after the increment. While return i++ return i then icrement it.

Try to add click event out of addElements() function and try once.

Nonsense create an element using JavaScript and then use jQuery function to transform it into a jQuery object. You can let jQuery create the element directly for you.

eCreditT[i] = $('<div>').addClass("cCreditTransaction").appendTo(eCreditSystem);

Also, since eCretitT[i] is already a jQuery element, no need to call the jQuery function again.

eCreditT[i].on('click', function () {
    creditTransactionSlideBackIn(eCreditT[i], 150);
});

If you already tried on, bind, live and click methods, then maybe the called function is your problem. Try to put a console.log() or an alert() inside the function to make sure the click event is actually happening. If it happens then the function creditTransactionSlideBackIn() is your problem.

EDIT

The problem is when the event takes place, i is not the original variable anymore.

function addElements (arrayIndex)
{
    eCreditT[i] = $('<div>').addClass("cCreditTransaction").appendTo(eCreditSystem);
    eCreditT[i].attr ('id', ('trans' + i));

    eCreditT[i].data ('id', i);    // Store the id value to a data attribute

Then when you call the function you can refer to the data attribute instead of the i variable:

/* ***** THE PROBLEM AREA ***** */
    eCreditT[i].on ('click', function ()                 // if user clicks on the transaction box
    {
        creditTransactionSlideBackIn ($(this).data('id'), 150);                    // slide back in animation
    });
    return i++;
}

try to bind parent div and then use if($e.target).is('some')){}, it will act as .live, like this:

$(eCreditSystem).bind('click', function (e){
    if($(e.target).is('.cCreditTransaction')) {
        creditTransactionSlideBackIn ($(e.target), 150);              
    }
});

of course you'll need in a minute larger if for checking if clicked dom el is a child of .cCreditTransaction, like this:

if($(e.target).parents().is('.cCreditTransaction')){}

Try this:

$(eCreditT[i]).live('click', function() {
   creditTransactionSlideBackIn(eCreditT[i], 150);
});
发布评论

评论列表(0)

  1. 暂无评论