0

我正在为健全的浏览器提供的各种功能构建一个 IE shim(不幸的是,我处于必须支持 IE7 的位置)。

我在 jQuery 原型上定义了以下方法定义:

    $.fn.textWidth = function(){
         //some logic in here
    }

    shimSelect = function(selector){
       $(selector).on('focus', function(){
            $(this).each(function(index, element){
                   if(element.textWidth() > element.width){
                        //more logic
                   }
            }
        }
     }

     if (!$.support.leadingWhitespace) {
         $(function() {
             shimSelect("");
         });
     }

通过明智地添加各种 console.logs,我已经确定直接在调用 textWidth 之前,在我的情况下,该元素是一个 HTMLElement(特别是 HTMLSelectElement)。

但是,它拒绝调用 textWidth(),Object does not support this property or method在 IE 和

    Uncaught TypeError: Object #<HTMLSelectElement> has no method 'textWidth' shim.js:104
        (anonymous function) togo_ie_shim.js:104
        jQuery.extend.each jquery.js:612
        jQuery.fn.jQuery.each jquery.js:242
        (anonymous function) togo_ie_shim.js:103
        jQuery.event.dispatch jquery.js:3064
        elemData.handle.eventHandle

在 Chrome 上

我的问题是,我的代码有什么问题?为什么会失败?以及如何正确实施类似的垫片?

4

1 回答 1

1

each函数不会给你 jquery 对象作为参数,它是一个 DOM 对象。

jQuery.each( collection, callback(indexInArray, valueOfElement) )

您已经扩展了 jquery 对象,因此,元素上没有定义函数 textWidth。

尝试使用 :$(element)代替。

于 2013-02-26T03:11:37.310 回答