0

我有一些元素可以动态地添加到我网站上的某个区域,但是当它们被添加时我需要一些东西来监听,这样它就可以触发一个事件。

元素是这样前置的

something.prependTo('#area')

被前置的元素是这样的

<div id="box1" class="box new">

我已经尝试了以下每一项都没有运气......

$('.new').on(playSound());
$('.new').bind('DOMSubtreeModified', playSound());
$('.new').each(playSound());
$('.new').live(playSound());
$('.new').livequery(playSound());

声音在页面最初加载时播放,但在添加元素时不播放。

4

3 回答 3

2
$('#area').on('DOMNodeInserted', function(e) {//whenever an element is inserted
    if ($(e.target).is('.new')) {             //check if it has the right class
        playSound();                          //and play sound
    }
});

它在 IE 中不起作用,因为没有支持,如果我没记错的话,突变事件已被弃用,所以也不能保证未来的支持?

于 2013-04-02T14:44:13.983 回答
1

我会说:

function prependWithSound(something){
    something.prependTo('#area')
    playSound();
}

然后调用 prependWithSound(something)而不是 something.prependTo('#area').

为什么要让生活变得更艰难?

于 2013-04-02T14:35:59.440 回答
1

LiveQuery会这样做,但正如@Bergi 指出的那样,您必须删除括号:

$('.new').livequery(playSound);

这是一个例子。

于 2013-04-02T14:57:38.783 回答