0

我对 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 的每个跨度对应于从“游戏”文本字段中获得的每个值。在这里,单击带有删除游戏的链接没有任何作用。它实际上应该像上面那样进入函数,并显示一个警报,但它从未发生过。

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

非常感谢您提前!!

4

3 回答 3

1

你需要使用.on这种方式

$("#showgames").on('click','.removegame',function(){
        // The will happen now
        alert("hi");
});
于 2013-04-19T19:30:53.333 回答
1

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

$("#showgames").on('click', '.removegame', function(){
    // Your code here
    console.log("hello");
});
于 2013-04-19T19:32:46.690 回答
-1

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

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

在您的选择功能内。

于 2013-04-19T19:32:56.700 回答