【问题标题】:jQuery can't find() inside a plugin?jQuery 在插件中找不到()?
【发布时间】:2012-02-12 04:11:31
【问题描述】:

我对 jQuery 很陌生,我正在开发一个插件(供我自己使用),用于设置 DOM 元素 html() 与 ajax 调用返回的内容。示例:

<span id="a" class="scalar">?</span>
<span id="b" class="scalar">?</span>
<span id="c" class="scalar">?</span><!-- this will not be updated -->

如果stats.php 将返回一个像这样的 JSON 对象:{ a : 3, b : 7 } 生成的 HTML 将是(每个对象属性将匹配调用插件的选择中的 id):

<span id="a" class="scalar">3</span>
<span id="b" class="scalar">7</span>
<span id="c" class="scalar">?</span><!-- this will not be updated -->

这是插件的调用和定义。 问题是:为什么find()不能正确选择要更新的元素?

<script type="text/javascript">
   $(document).ready(function() {
      $('.scalar').scalar({ url : '../REST/stats.php' });
   });
</script>

(function($) {

    $.fn.scalar = function(options) {

        var opt = $.extend({
            url : 'REST/stats.php',
            type : 'POST',
            context: this,
            dataTypeString : 'json'
        }, options);

        $.ajax($.extend(opt, {
            success : function(obj) {
                for(k in obj) {
                    if(!obj.hasOwnProperty(k)) continue;
                    console.log(this.find('#' + k));
                }
            }
        }));

        return this.each();
    };

})(jQuery);

【问题讨论】:

    标签: jquery jquery-plugins jquery-selectors


    【解决方案1】:

    因为find 寻找后代元素,而您要寻找的元素不是后代(它们都是彼此的兄弟)。请改用filter

    console.log(this.filter('#' + k));
    

    this 将是一个包装了一组 DOM 元素的 jQuery 对象。除非这些元素中的一个或多个包含带有id 的后代元素,否则您将使用find 查找它,否则它将不起作用。您需要查看元素本身,这就是 filter 所做的。

    【讨论】:

      猜你喜欢
      • 2018-09-11
      • 2011-04-11
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多