Javascript .next()不';t在.each()循环中工作

Javascript .next()不';t在.each()循环中工作,javascript,jquery,Javascript,Jquery,我正在使用引导工具提示插件来显示工具提示。 我的HTML是这样的: <a href="#" data-role="tooltip" title="">actions</a> <div class="user-actions"> <a class="icon" href="/edit"> <i class="icon-pencil"></i> </a> <a class

我正在使用引导工具提示插件来显示工具提示。 我的HTML是这样的:

<a href="#" data-role="tooltip" title="">actions</a>
<div class="user-actions">
    <a class="icon" href="/edit">
        <i class="icon-pencil"></i>
    </a>
    <a class="icon" href="/delete">
        <i class="icon-trash"></i>
    </a>
</div>
我想让我的脚本做的是循环遍历每个
选择器,然后找到紧跟其后的选择器,获取其html并将其作为
title
属性的值

但是

它就是不起作用。 控制台错误显示:

Uncaught TypeError: Object [object HTMLAnchorElement] has no method 'next'

我做错了什么?我怎样才能让它工作

引用原始dom元素,在对其使用jquery方法之前,需要先对其进行包装

$('a[data-role=tooltip]').each(function(){
    // cache the jquery object
    var $this = $(this);
    var content = $this.next().html()
    $this.attr('title', content);
});

引用原始dom元素,在对其使用jquery方法之前,需要先对其进行包装

$('a[data-role=tooltip]').each(function(){
    // cache the jquery object
    var $this = $(this);
    var content = $this.next().html()
    $this.attr('title', content);
});

不是jQuery对象。它是一个DOM元素。你应该这样做:

$('a[data-role=tooltip]').each(function() {
    $(this).attr('title', $(this).next().html());
});

虽然这样更好:

$('a[data-role=tooltip]').attr("title", function() {
    return $(this).next().html();
});

…因为它只需要调用一次
.attr()

这不是jQuery对象。它是一个DOM元素。你应该这样做:

$('a[data-role=tooltip]').each(function() {
    $(this).attr('title', $(this).next().html());
});

虽然这样更好:

$('a[data-role=tooltip]').attr("title", function() {
    return $(this).next().html();
});
…因为它只需要调用一次
.attr()

只需将其包装:

$(this)
而不是
this

只需将其包装:


$(this)
而不是
this

查看以下文档:

.each()
方法旨在使DOM循环构造简洁且不易出错。调用时,它会迭代作为jQuery对象一部分的DOM元素。每次回调运行时,都会从0开始传递当前循环迭代更重要的是,回调是在当前DOM元素的上下文中触发的,因此关键字
this
引用该元素。


因此,
这个
引用了一个
HTMLElement
对象(或
HTMLElement
的子类,正如您在记录的异常中看到的那样)。您需要像
$(this)
那样包装它,然后才能对其调用jQuery方法。

查看文档了解:

$('a[data-role=tooltip]').each(function(){
    // cache the jquery object
    var $this = $(this);
    var content = $this.next().html()
    $this.attr('title', content);
});
.each()
方法旨在使DOM循环构造简洁且不易出错。调用时,它会迭代作为jQuery对象一部分的DOM元素。每次回调运行时,都会从0开始传递当前循环迭代更重要的是,回调是在当前DOM元素的上下文中触发的,因此关键字
this
引用该元素。


因此,
这个
引用了一个
HTMLElement
对象(或
HTMLElement
的子类,正如您在记录的异常中看到的那样)。在能够调用jQuery方法之前,您需要将其像
$(this)
一样包装。

this
不是jQuery对象。使用
$(this)
代替
this
不是jQuery对象。使用
$(this)
而不是多次调用
$()
,最好只调用一次,然后缓存结果并使用应该避免多次调用
$()
——最好只调用一次,然后缓存结果并使用它
$('a[data-role=tooltip]').each(function(){
    // cache the jquery object
    var $this = $(this);
    var content = $this.next().html()
    $this.attr('title', content);
});