【问题标题】:jQuery selector with concatenation not working in IE8带有连接的jQuery选择器在IE8中不起作用
【发布时间】:2012-07-04 09:19:12
【问题描述】:

我正在使用 jQuery 1.7.2

这行代码在 IE9、Chrome 和 Firefox 上运行良好:

$('.' + product.id + '#' + this).text("foo");

product.id 是表示类的字符串,this 是表示 id 的字符串。

该行在 $.each 循环内,我没有发布该函数的整个代码,因为它相当大,错误恰好位于该行。

使用此循环动态创建的选择器示例如下:

$('.price#servicesPerMonth').text("foo");

在 IE8 中出现以下错误:

Unexpected call to method or property access.  
jquery-1.7.2.js, line 5847 character 5

jQuery中的代码是这样的:

append: function() {
    return this.domManip(arguments, true, function( elem ) {
        if ( this.nodeType === 1 ) {
            this.appendChild( elem );
        }
    });
},

第 5847 行是this.appendChild( elem );

我认为问题出在连接 jQuery 选择器中的 this 变量,但我真的不知道解决此问题的替代方法。

有什么建议吗?

【问题讨论】:

  • this 是什么?一个字符串?
  • 为什么要使用class和id?只需使用 id 就足够了,因为您的 html 具有唯一的 id,对吧?
  • 目标元素是否有可能是 html5 元素,例如 section?当我使用没有垫片的 html5 元素时,我可以在 IE8 中重现这一点
  • 是的,this是字符串,目标元素不是html5元素。

标签: jquery internet-explorer-8 cross-browser concatenation


【解决方案1】:

尝试使用

('.' + product.id + ' #' + this.id).text("foo");

('.' + product.id + ' #' + this.attr('id')).text("foo");

没关系,注意#前面的空格

【讨论】:

  • 你怎么知道类选择器和ID选择器之间需要有一个空格?你怎么知道this 是什么? OP 需要先更新问题,然后才能知道您的答案是否接近。
  • 啊,我的错,我以为这是一个对象。但这是一个关键字,你不能用它来保存字符串值,最好使用任何其他名称
  • @Sachin 错误:您可以将this 设置为字符串:(function(){return this}).call("test") 返回一个String 对象。(function(){'use strict';return this}).call("test") 返回一个原始字符串。
猜你喜欢
  • 2013-03-08
  • 1970-01-01
  • 1970-01-01
  • 2012-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-20
相关资源
最近更新 更多