.next()在.each()循环中不起作用

c00*_*web 0 javascript jquery

我正在使用bootstrap-tooltip插件来显示工具提示.我的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>
Run Code Online (Sandbox Code Playgroud)

我的JS:

$(function() {
    $('[data-role=tooltip]').tooltip({
        html: true,
        placement: 'bottom',
        trigger: 'click'
    });

    $('a[data-role=tooltip]').each(function(){
        var content = this.next().html()
        this.attr('title', content);
    });
});
Run Code Online (Sandbox Code Playgroud)

我希望我的脚本要做的是循环遍历每个<a data-role='tooltip' title=''>选择器,然后立即找到跟随选择器,获取其html并将其作为title属性值.

它只是不起作用.控制台错误说:

Uncaught TypeError: Object [object HTMLAnchorElement] has no method 'next'
Run Code Online (Sandbox Code Playgroud)

我做错了什么?我怎么能让它发挥作用?

use*_*012 5

this不是jQuery对象.这是一个DOM元素.你会这样做:

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

虽然这更好:

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

...因为它只需要你拨打.attr()一次.

  • 应避免多次调用`$()` - 最好调用一次,然后缓存结果并使用它 (2认同)