我正在使用jQuery重新格式化一些非常糟糕的HTML。我需要将同级<font>
元素拼接在一起。我试过这个代码:
$('font+font').each(function() {
this.html().appendTo( this.prev() );
this.remove();
});
但它给了我这个错误:TypeError:"undefined"不是函数(计算"this.html()")
以下是HTML:的示例
<font>This fragment </font><font>is actually one element.</font>
更新
我用$(this)
更新了代码,但它仍然不起作用。当我运行这个代码
$('font+font').each(function() {
$(this).html().appendTo( $(this).prev() );
$(this).remove();
});
我得到这个错误:TypeError:"undefined"不是一个函数(正在评估"$(this).html().appendTo($(this).prve())")
this
必须封装在jQuery对象中,然后才能对其使用jQuery方法.html()
返回一个字符串。不能在不换行的情况下对字符串使用jQuery方法。请改用$this.prev().append( $this.html() )
- 当多次使用
$(this)
时,明智的做法是将$(this)
存储在临时变量中。在jQuery对象前面加一个美元符号是惯例
代码:
$('font+font').each(function() {
var $this = $(this);
$this.prev().append( $this.html() );
$this.remove();
});
当您使用each语句时,它会将this
作为DOM元素而不是jQuery对象返回。必须对jQuery对象调用.html()
。因此,修复的第一部分是将this
转换为带有$
符号的jQuery元素。
$(this).html(); //don't use this.html();
第二个问题是html()
返回一个字符串。不能对字符串调用AppendTo()
,只能对jQuery对象调用。由于您使用的是.html()
,我假设您想要的是字符串内容,而不是完整内容。如果是这样的话,Rob的回答更合适。
this.textContent = $(this).prev().html() + this.textContent; // prepend siblings content
最后的代码看起来是这样的:
$('font+font').each(function() {
this.textContent = $(this).prev().html() + this.textContent;
$(this).prev().remove();
});
http://jsfiddle.net/b6vLL37k/1
您需要使用$(this)
而不是this
您需要使用$(this)
for jQuery来帮助您。
我无法修复您的代码。像这样的东西怎么样:
var text = '';
$('font').each(function() {
text += $(this).text();
});
console.log($('<p />').text(text));