使用JQuery创建的Div不起作用

时间:2013-04-19 19:29:08

标签: jquery html jquery-ui jquery-autocomplete

我对JQuery有一个奇怪的问题,我试图使用一个文本字段,它使用JQuery UI的自动完成来显示建议,并将每个选定的文本值附加到div。除了每个文本标签,还有一个删除链接,但我无法让它工作。

自动完成功能就像魅力一样:

 $( "#games" ).autocomplete({
                source: "<?php echo base_url('game/game/autocomplete'); ?>",
                dataType: "json",
                type: "POST",
                minLength: 1, // how many character when typing to display auto complete
                // handling the select
                select: function( event, ui ) {
                  $('#showgames').append('<span id="'+ui.item.value+'">'+ui.item.value+'<a href=# class="removegame">Remove</span>');
                    $('#games').val('');
                    return false;
                }
            });
            // removing game items
            $('.removegame').click(function(){
                // The following never happens
                    alert("hi");
                });

  <div id="showgames">
       // anchor links are generated by jquery here, within individual spans.
       // these are not working
            </div>

            <div id="testing">
                // This works
                <a class=removegame href=#>Test link</a></span> 
            </div>

自动填写字段:(游戏)

            <td align="left"><label for="genres">Genre(s):</label></td>

showgames div的每个范围对应于从“games”文本字段获得的每个值。在这里,点击删除游戏的链接什么都不做。它应该实际上进入上面的功能,并显示一个警报,但它永远不会发生。

相反,如果我在页面上使用类removegame创建一个锚标记项,它就可以了。但是当它使用jQuery生成时,它不起作用。我疯了。有人可以帮助我吗?

非常感谢你!!

3 个答案:

答案 0 :(得分:1)

您需要以这种方式使用.on

$("#showgames").on('click','.removegame',function(){
        // The will happen now
        alert("hi");
});

答案 1 :(得分:1)

由于您的链接是动态创建的,因此当将删除功能附加到链接时,它们不在身边。相反,最好编写代码以在发生单击事件时检查元素上的removegame类:

$("#showgames").on('click', '.removegame', function(){
    // Your code here
    console.log("hello");
});

答案 2 :(得分:-1)

在您的选择功能中,您需要在新添加的链接上连接事件。基本上,您可以移动此代码:

    // removing game items
    $('.removegame').click(function(){
        // The following never happens
            alert("hi");
        });

在您的选择功能中。