考虑以下DOM操作问题:我需要在点击某个链接后创建一个span标记。由于加快了进程,我更喜欢使用document.createElement()
(纯Javascript)而不是创建HTML元素的Jquery方法。以下代码编译正确但不起作用(可能是因为Javascript和Jquery之间的干扰)。任何帮助将不胜感激。
<body>
<a href="#">Create thumbnails</a>
<script type="text/javascript">
$('a').click(function(e) {
var newSpan=null;
newSpan = document.createElement('span');
newSpan.setAttribute('class','themes');
$('.themes').html('themes');
$('.themes').appendTo('body');
return false;
});
</script>
</body>
答案 0 :(得分:3)
尝试以下方法:
<body>
<a href="#">Create thumbnails</a>
<script type="text/javascript">
$('a').click(function(e) {
var newSpan=null;
newSpan = document.createElement('span');
newSpan.setAttribute('class','themes');
$(newSpan).html('themes');
$(newSpan).appendTo('body');
return false;
});
</script>
</body>
使用$(".themes")
作为选择器会在文档中搜索具有“主题”类的元素,而不是函数中的newSpan
元素。您必须使用newSpan
作为选择器,直到将其附加到文档中。
答案 1 :(得分:2)
在jQuery可以对它做任何事情之前,你需要将它插入到你的文档中。
答案 2 :(得分:2)
我相信这是因为jQuery“$”函数正在查找包含已经在文档正文中的类“themes”的任何内容。它找不到任何东西,因为你之后只试图追加它。
答案 3 :(得分:1)
$('.themes').appendTo('body');
使用这段代码,你告诉jQuery找到类'themes'的所有元素并将它们附加到body,但是为了找到它们,元素需要已经存在于DOM中,看起来情况并非如此。在使用jQuery查找元素之前,您应该创建元素并通过JavaScript将其附加到DOM。
答案 4 :(得分:1)
$('a').click(function(e) {
var newSpan=null;
newSpan = document.createElement('span');
newSpan.setAttribute('class','themes');
$('body').append(newSpan);
$('.themes').html('themes');
e.preventDefault();
});
答案 5 :(得分:1)
dom中没有新元素 将其附加到文档,然后查看它是否有效 +如果你使用jquery,为什么不一直使用它?
$('a').click(function(e) {
$('span')
.attr('class','themes')
.html('themes');
.appendTo('body');
e.preventDefault();
});
答案 6 :(得分:1)
<body>
<a href="#">Create thumbnails</a>
<script type="text/javascript">
$('a').click(function(e) {
var newSpan=null;
newSpan = document.createElement('span');
newSpan.setAttribute('class','themes');
//You can't manipulate span.theme because span does still not exist
//$('.themes').html('themes');
//$('.themes').appendTo('body');
//Create span on the body and then you can manipulate it
document.body.appendChild(newSpan);
$('.themes').html('themes');
return false;
});
</script>
</body>
或者:
<body>
<a href="#">Create thumbnails</a>
<script type="text/javascript">
$('a').click(function(e) {
$(this).after('<span class="themes">thumb</span>');
});
</script>
</body>
答案 7 :(得分:1)
您的代码存在以下几个问题:
getAttribute()
和setAttribute()
已被破坏。请改用className
属性。但是,在这个实例中避免使用jQuery所获得的性能提升将是微不足道的,除非你在点击处理程序中做的比你发布的要多得多。但是,对于它的价值,这里有一些修改后的代码:
$('a').click(function(e) {
var newSpan = document.createElement('span');
newSpan.className = 'themes';
newSpan.innerHTML = 'themes';
document.body.appendChild(newSpan);
return false;
});
答案 8 :(得分:1)
将您刚刚创建的范围包装为jQuery对象,这样您就可以对其执行jquery操作,甚至不会将其附加到正文中。
<body>
<a href="#">Create thumbnails</a>
<script type="text/javascript">
$('a').click(function(e) {
var newSpan=null;
newSpan = document.createElement('span');
newSpan.setAttribute('class','themes');
var jqNewSpan = $(newSpan);
jqNewSpan.html('themes');
jqNewSpan.appendTo('body');
return false;
});
</script>
</body>