0

I am creating some divs dynamically and Im attaching onclick functions to them. Is there any way to attach functions which take parameters in this way?

If I just create the div in html I can attach a function and it works perfectly. I can also attach simple functions without parameters dynamically and they work perfectly.

How could I attach this function which takes 'this' as a parameter to my div??

Would anyone have any suggestions???

onclick="playSound(this)"

function playSound(el){
var soundId = $(el).html();
if ( soundId == ('d')){
d.playclip()
}
else if ( soundId == ('a')){
a.playclip()
}
else if ( soundId == ('n')){
n.playclip()
}

I can attach a function like this and it works fine.

$(".myDiv").live("click", function(){
alert('hello');
});

Any help would be hugely appreciated!!! Thanks!!

2
  • The last example is missing () after function Commented Jan 6, 2013 at 20:39
  • soundId == ('d') is same as soundId == 'd' Commented Jan 6, 2013 at 20:41

3 Answers 3

3

For this specific case you could use something like:

$(".myDiv").click(function(){
  playSound(this);
});

If you refactor your code dropping el and using this in this way:

function playSound() {
    var soundId = $(this).html();
    if (soundId == ('d')) {
        d.playclip()
    } else if (soundId == ('a')) {
        a.playclip()
    } else if (soundId == ('n')) {
        n.playclip()
    }
}

You could use it directly.

$(".myDiv").click(playSound);
Sign up to request clarification or add additional context in comments.

Comments

1

You can attach some data to your elements using $(el).data('some-key', 'some-value') and

$(".myDiv").live("click", function() {
   alert($(this).data('some-key'));
})

In this way you can attach data to an element and make use of it later.

Comments

1

absolutely. It's called javascript's bind function:

playSound.bind(this, arg1, arg2, ...)

Another useful function that is similar is jquery's proxy function. This only keeps track of the scope though and doesn't allow you to send other parameters:

$.proxy(playSound, this)

1 Comment

The stuff about .bind() is correct, but it's not a jQuery feature. It's native JavaScript. There's a somewhat similar jQuery feature called $.proxy() however.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.