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

标签 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>

我的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);
    });
});

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

但是

这根本行不通。 控制台错误显示:

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

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

最佳答案

this 不是 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() 一次。

关于javascript - .next() 在 .each() 循环中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18767275/

相关文章:

javascript - 多个 if 语句的替代方案

javascript - 屏幕外 div 不适用于 html2canvas

javascript - jquery ajax : redirect with json - unexplainable behaviour?

javascript - jquery 弹出必须按两次“确定”两次才能使其消失

jquery - KnockoutJs 和 jqTransform

javascript - 使用 val(value) 设置文本框的值不起作用

javascript - 如何提醒按钮内联

javascript - 如何使用 javascript 更新 parse.com 中的当前对象?

javascript - 如何管理容器中的 html 元素

javascript - 有没有办法使用 Firebug 查看 [object][object] 中包含的信息?