在JQuery中使用appendTo()添加元素然后立即删除它...解决方案?

The*_*pes 0 php jquery appendto

这可能是一个菜鸟问题,但是我如何实现下面的appendTo()函数并不能按预期工作.基本上,它添加了元素并立即再次删除它.它眨眼,你想念它的东西.

任何人都可以理解为什么会这样吗?

这是调用函数的位置:

<?php foreach ($words as $word) {
echo    "<li class='$word[0]'><a href='' onclick='add_to();'>$word</a></li>";
} 
Run Code Online (Sandbox Code Playgroud)

这里是函数本身(几乎取自jQuery教程网站:

function add_to () {
        $('<h1>Test</h1>').appendTo('.ad_text');
    }
Run Code Online (Sandbox Code Playgroud)

我的第一个想法是调用一个调用document.ready()的脚本,它会清除add_to()函数?该脚本位于add_to()之上,如下所示:

$(document).ready(function(){

        //when a link in the filters div is clicked...
        $('#filters a').click(function(e){

            //prevent the default behaviour of the link
            e.preventDefault();

            //get the id of the clicked link(which is equal to classes of our content
            var filter = $(this).attr('id');

            //show all the list items(this is needed to get the hidden ones shown)
            $('#content ul li').show();

            /*using the :not attribute and the filter class in it we are selecting
            only the list items that don't have that class and hide them '*/
            $('#content ul li:not(.' + filter + ')').hide();

        });

    });
Run Code Online (Sandbox Code Playgroud)

那里可能存在相互矛盾的代码?对不起 - Javascript新手,并尝试快速拼凑一些东西.

TIA,安迪

Nal*_*lum 5

您的链接正在重新加载页面.试试这个(将#添加到href属性)

foreach ($words as $word) {
    echo    "<li class='$word[0]'><a href='#' onclick='add_to();'>$word</a></li>";
}
Run Code Online (Sandbox Code Playgroud)