jQuery插件this.attr("id")未定义

bot*_*bot 1 javascript jquery jquery-plugins

为什么要调用console.log(this.attr("id"));未定义的调用?

(function( $ ) {
    $.fn.fs_suggest = function(options) {
        console.log(this.attr("id"));
    };
})( jQuery );

$("#places_search").fs_suggest();
Run Code Online (Sandbox Code Playgroud)

这是HTML:

<div class="search_container" id="search">
    <form data-remote="false" method="get" action="/search">
        <input type="text" placeholder="search places" name="query" id="places_search">
        <input type="submit" value="search">
    </form>
</div>
Run Code Online (Sandbox Code Playgroud)

我正在尝试获取对调用.fs_suggest()函数的元素的引用,在本例中为$("#places_search")

Ell*_*lle 8

我想你想要这个:

console.log($(this).attr("id"));
Run Code Online (Sandbox Code Playgroud)

除非我弄错了,否则this引用一个DOM元素(没有attr函数),而$(this)获取实际的jQuery对象(确实如此).


如果这个(或者我的意思是this?呵呵......)不起作用那么你只是在错误的选择器上调用该函数.


进一步细读jQuery文档后,您的问题似乎出现在您提供给我们的上下文之外的其他地方.你是否在DOM正确加载之前调用了你的插件?(例如在...之外$(document).ready())