Object不支持此属性或方法

时间:2011-09-14 02:59:51

标签: javascript jquery internet-explorer

我遇到的问题是IE无法使用以下代码。如果元素为空,代码基本上隐藏了一个div,你会发现除了IE之外它都可以工作。

//hide webapp item if empty
if ($("#features").html().trim()) {} else {
    $("#f-h").hide()
}
if ($("#application").html().trim()) {} else {
    $("#a-h").hide()
}
if ($("#tech-specs").html().trim()) {} else {
    $("#t-h").hide()
}
if ($("#downloads").html().trim()) {} else {
    $("#d-h").hide()
}
if ($("#custom-field").html().trim()) {} else {
    $("#c-f").hide()
}

要查看其效果的网页是webpage

为什么ie不喜欢这个或更好的方法的任何提示将不胜感激。

3 个答案:

答案 0 :(得分:2)

我的猜测是Internet Explorer正在以不同方式解析这些行,从而导致错误。解决方法是始终使用分号来标记线条的末端。我还清理了一些代码,用if-nots替换了空的if / else块。

//hide webapp item if empty

if (!$("#features").html().trim()) {
  $("#f-h").hide();
}

if (!$("#application").html().trim()) {
  $("#a-h").hide();
}

if (!$("#tech-specs").html().trim()) {
  $("#t-h").hide();
}

if (!$("#downloads").html().trim()) {
  $("#d-h").hide();
}

if (!$("#custom-field").html().trim()) {
  $("#c-f").hide();
}

答案 1 :(得分:1)

您可以根据HTML的结构大大简化JavaScript。如果要隐藏的元素始终位于彼此附近/旁边,则可以为这些部分分配类(“功能”,“应用程序”,“技术规格”等),例如, “section”,以及你想要隐藏的元素(“f-h”,“a-h”,“t-h”等),例如“隐藏我”,并使用一个函数来完成工作:

$('.section').each(function() {
    if ($(this).is(':empty')) {
        $(this).closest('.hide-me').hide();
    }
});

我不一定喜欢这个解决方案,但你也可以使用你想要测试的部分的地图,如果它们在HTML中的随机位置就会隐藏:

var items = [
    { key: '#features', value: '#f-h' },
    { key: '#application', value: '#a-h' },
    { key: '#tech-specs', value: '#t-h' },
    { key: '#downloads', value: '#d-h' },
    { key: '#custom-field', value: '#c-h' }
];

$.each(items, function(index, element) {
    if ($(element.key).is(':empty')) {
        $(element.value).hide();
    }
});

Here's a working example上述代码。

我知道这不能回答你的问题,但我只想给我0.02美元。

答案 2 :(得分:1)

jQuery html()方法只返回一个包含HTML的字符串。

JavaScript字符串没有trim()方法。

如果你想在javascript的String对象中引入一个。你可以这样做:

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

^^^没有对此进行测试,但我很确定它会完成这项工作。