在 JQuery 中使用appendTo()添加元素然后立即删除它......解决方案?
这可能是一个菜鸟问题,但是我如何实现下面的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 新手,并试图快速拼凑一些东西
,安迪。
This is probably a noob question, but how I've implemented the appendTo() function below doesn't work as expected. Basically, it added the element and instantly removed it again. It's blink and you miss it stuff.
Can anyone understand why this might be happening?
Here's where the function gets called:
<?php foreach ($words as $word) {
echo "<li class='$word[0]'><a href='' onclick='add_to();'>$word</a></li>";
}
And here's the function itself (pretty much taken from the jQuery tutorial site:
function add_to () {
$('<h1>Test</h1>').appendTo('.ad_text');
}
My first thought is that a script that calls document.ready() is called, which wipes out the add_to() function? That script is above add_to(), and is this:
$(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();
});
});
Possibly a conflicting bit of code there? Sorry - new to Javascript, and trying to cobble something together quickly.
TIA, Andy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的链接正在重新加载页面。
试试这个(将 # 添加到 href 属性)
Your link is reloading the page.
Try this (added # to the href attribute)
我不能肯定地说,但您可能会使用 document.ready 函数中的函数覆盖 onclick 属性中定义的 click 函数。
I can't say for sure but you might be overriding the click function that you defined in the onclick attribute with the one in the document.ready function.