【问题标题】:Using appendTo() in JQuery adds element then immediately removes it...solution?在 JQuery 中使用 appendTo() 添加元素然后立即将其删除...解决方案?
【发布时间】:2011-03-21 12:45:30
【问题描述】:

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

谁能理解为什么会发生这种情况?

这里是函数被调用的地方:

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

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

function add_to () {
        $('<h1>Test</h1>').appendTo('.ad_text');
    }

我的第一个想法是调用了一个调用 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();

        });

    });

那里可能有一些冲突的代码?抱歉 - Javascript 新手,正在尝试快速拼凑一些东西。

TIA,安迪

【问题讨论】:

  • add_to 在哪里被调用?
  • 请向我们展示 HTML 标记...而不是 PHP。
  • @balupton add_to 从上面的 php sn-p 中的 onclick 事件中调用。 @J-P HTML 在上面的 PHP 中。您需要更多的 HTML 吗?

标签: php jquery appendto


【解决方案1】:

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

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

【讨论】:

  • 所以去掉href中的#?
  • 没有问题应该把你的代码然后我的,现在会更清楚。
  • @Nalum @NickCraver 将内容附加到 div 时,上述解决方案运行良好。但是,当我尝试将相同的内容添加到 HTML 中的 textarea 标记时,什么也没有发生。知道为什么会这样吗?
  • 在处理 onclick 事件的函数末尾添加 return false;。这将阻止点击链接(并在 url 中添加丑陋的 #)。
  • @The Pied Pipes: appendTo & append 创建文本区域无法显示的 html。如果要附加到文本区域,则必须使用 html 实体,例如jsfiddle.net/T9XBu
【解决方案2】:

我不能肯定,但您可能会用 document.ready 函数中的函数覆盖您在 onclick 属性中定义的点击函数。

【讨论】:

  • 重要的是要区分他/她不是覆盖,而是添加一个点击处理程序,如果该链接在#filters 内是。
  • 是的,尼克说得对。 Nalum 添加的哈希锚点起作用了。但是,在尝试将 appendTo() 添加到 textarea 标记时确实遇到了麻烦。有什么建议吗?
猜你喜欢
  • 2017-01-16
  • 2011-02-16
  • 2015-09-29
  • 2015-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多