开发者

How do I add a click handler to a new element when I create it?

How do I add a click handler to a new element when I create it? This is what I have tried, but it does not work as expected:

DeCheBX = $('MyDiv').insert(new Element('input', {
    'type': 'checkbox',
    'id': "Img" + obj[i].Nam,
    'value': obj[i].IM,
    'onClick': SayHi(this)
}));
document.body.appendChild(DeCheBX);
DeImg = $('MyDiv开发者_JAVA技巧').insert(new Element('img', {
    'id': "Imgx" + obj[i].Nam,
    'src': obj[i].IM
}));
document.body.appendChild(DeImg);
}
SayHi = function (x) {
    try {

        if ($(x).checked == true) {
            alert("press" + x);
        }

    }
    catch (e) {
        alert("error");


The way you are adding the handler, the function is actually being invoked when you create the element. When you write SayHi(this) it actually runs the function with the current value of this. What I'd suggest is wrapping the invocation of the handler into an anonymous function defined when you create the element. That way the SayHi code won't actually be executed until the click handler is invoked. Replace this:

'onClick': SayHi(this)

with

'onClick': function() { SayHi(this); } 


'onClick': SayHi.bind(this)

Hi there!

Just use '.bind' before your params! An event handler has to be a function, not the return of your function. Create a functions that will have the params you want baked in by using .bind.

-Rob


this will be window because that is the invoker of the onclick function.

bind will fix this if you are using prototype or other libraries but for those who want a native solution, you need to break up your code a little to simplify it:

var myElem = new Element('input', {
    'type': 'checkbox',
    'id': "Img" + obj[i].Nam,
    'value': obj[i].IM
}

myElem.onclick = function() {sayHi(myElem )};

DeCheBX = $('MyDiv').insert(myElem);


var myElem = new Element('input', {'type': 'checkbox','id': "Img" + obj[i].Nam,'value': obj[i].IM }).observe('click',sayHi);
$('MyDiv').insert(myElem);

SayHi = function () {
try {

    if (this.checked == true) {
        alert("press" + this);
    }

}
catch (e) {
    alert("error");


with prototype will something like this

$('id').observe('click',function(event){
      alert("make something cool");
}.bind(this))

or the second option

Element.observe('id',"click",function(){
    alert("make something cool");
}.bind(this))

both works... cheers =)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜