[英]Attach function with parameters to dynamically created div with jQuery
我正在动态创建一些div,我将onclick函数附加到它们。 有没有办法以这种方式附加使用参数的函数?
如果我只是用html创建div,则可以附加一个函数,它可以完美地工作。 我还可以动态附加没有参数的简单函数,它们可以完美地工作。
我怎样才能将这个以'this'作为参数的函数附加到div?
有人有什么建议吗???
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()
}
我可以附加一个这样的功能,并且效果很好。
$(".myDiv").live("click", function(){
alert('hello');
});
任何帮助将不胜感激!!! 谢谢!!
对于这种特定情况,您可以使用类似:
$(".myDiv").click(function(){
playSound(this);
});
如果您重构删除el
的代码并以这种方式使用this
:
function playSound() {
var soundId = $(this).html();
if (soundId == ('d')) {
d.playclip()
} else if (soundId == ('a')) {
a.playclip()
} else if (soundId == ('n')) {
n.playclip()
}
}
您可以直接使用它。
$(".myDiv").click(playSound);
您可以使用$(el).data('some-key', 'some-value')
和$(el).data('some-key', 'some-value')
附加数据到元素
$(".myDiv").live("click", function() {
alert($(this).data('some-key'));
})
这样,您可以将数据附加到元素上,并在以后使用它。
绝对。 它称为javascript的bind
函数:
playSound.bind(this, arg1, arg2, ...)
另一个类似的有用功能是jquery的代理功能。 但是,这仅跟踪作用域,并且不允许您发送其他参数:
$.proxy(playSound, this)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.