如何在jQuery中为动态创建的元素使用插件?

时间:2011-08-04 10:23:33

标签: jquery plugins contextmenu

我不知道该怎么办。我想这样做:

$('.message').contextMenu('myMenu1', {
    bindings: {
        'open': function(t) {
            alert('Trigger was '+t.id+'\nAction was Open');
        },
        'email': function(t) {
            alert('Trigger was '+t.id+'\nAction was Email');
        },
        'save': function(t) {
            alert('Trigger was '+t.id+'\nAction was Save');
        },
        'delete': function(t) {
            alert('Trigger was '+t.id+'\nAction was Delete');
        }
    }
});

用于动态创建的元素。

在AJAX的帮助下添加了具有类message的元素:

    $.post('index.php', {link: link, ajax: true},
        function(response) {
            $("#test").(response);
        }
    );

响应是服务器生成的HTML代码。

当Page加载firsrt时,html代码如下所示:

<!DOCTYPE HTML>
<html lang="ru-RU">
<head>
    <meta charset="UTF-8">
    <title>RTIT chat</title>
    <link rel="stylesheet" type="text/css" href="view/styles/style.css" media="all" />
    <script type="text/javascript" src="view/scripts/jquery/jquery-1.6.2.min.js"> </script>
    <script type="text/javascript" src="view/scripts/jquery/jquery.test.js"> </script>
    <script type="text/javascript" src="view/scripts/jquery/jquery.contextmenu.r2.packed.js"> </script>
    <script type="text/javascript" src="view/scripts/controller.class.js"> </script>
</head>
<body>
    <div id="ajaxLoadPlace">
    </div>
</body>
</html>

没有类message的元素。元素message将在controller.class.js的帮助下生成。

我在非dinamically创建的元素上尝试了这个插件,它运行正常!

怎么做?

首次更新DOM后,这只有一次...

1 个答案:

答案 0 :(得分:2)

请发布更多代码并更好地解释您的问题。为什么你不能在动态创建元素的同时调用该函数?如果这是一个问题,你可以尝试这个

$('.message').ready(function(){
    $(this).contextMenu('myMenu1', {
       bindings: {
        ...
        }
      }
    });
});

更新

$.post('index.php', {link: link, ajax: true},
    function(response) {
        $("#test").(response);
        $(".message").contextMenu('myMenu1', {
           ...
     });
});