0

我正在尝试编写一个针对 iFrame 的带有文件上传的简单表单。我已经涵盖了很多,但是 Internet Explorer 不支持动态生成的 iFrame 上的加载方法,所以我需要为它做一个替代方法。我的问题是 - 使用 Javascript 识别浏览器类型的最佳和最准确(加上轻量级)的方法是什么?

我知道Modernizr可以检查特定的方法/属性,但不太确定它在这种特定情况下是否有帮助。它有Modernizr.hasEvent(),但我不能用它来检查动态创建的元素。

4

3 回答 3

1

如果你想检查对特定事件的支持,你可以尝试这样的事情:

var isEventSupported = (function(){
    var TAGNAMES = {
      'select':'input','change':'input',
      'submit':'form','reset':'form',
      'error':'img','load':'img','abort':'img'
    }
    function isEventSupported(eventName) {
      var el = document.createElement(TAGNAMES[eventName] || 'div');
      eventName = 'on' + eventName;
      var isSupported = (eventName in el);
      if (!isSupported) {
        el.setAttribute(eventName, 'return;');
        isSupported = typeof el[eventName] == 'function';
      }
      el = null;
      return isSupported;
    }
    return isEventSupported;
  })();

这是上述内容的现场演示:

http://kangax.github.com/iseventsupported/

于 2012-08-13T11:40:54.560 回答
1

在我看来,最简单的检查方法是:

if ('onload' in iFrameVar)
{
    console.log('your code here');
}

其中 iFrameVar 是对 iframe 的引用,当然:

function elemSupportsEvent(elem,e)
{
    var f = document.createElement(elem);
    if (e in f)
    {
        console.log(elem + ' supports the '+ e + ' event');
        return true;
    }
    console.log(elem + ' doesn\'t support the '+ e + ' event');
    return false;
}
elemSupportsEvent('iframe','onload');//logs "iframe supports the onload event" in chrome and IE8

只是通过示例快速小提琴,您可以使用函数来检查各种元素的事件支持。

回应您的评论:如果您想检查动态内容 - 如在 ajax 回复中 - 您可以简单地使用该readystatechange事件:

xhr.onreadystatechange = function()
{
    if (this.readyState === 4 && this.status === 200)
    {
        var parent = document.getElementById('targetContainerId');//suppose you're injecting the html here:
        parent.innerHTML += this.responseText;//append HTML
        onloadCallback.apply(parent,[this]);//call handler, with parent element as context, pass xhr object as argument
    }
};
function onloadCallback(xhr)
{
    //this === parent, so this.id === 'targetContainerId'
    //xhr.responseText === appended HTML, xhr.status === 200 etc...
    alert('additional content was loaded in the '+ this.tagName.toLowerCase+'#'+this.id);
   //alerts "additional content was loaded in the div/iframe/td/whatever#targetContainerID"
}
于 2012-08-13T11:41:31.840 回答
0

使用navigator.userAgent. 它包含浏览器用户代理

if (navigator.userAgent.search("MSIE 6") == -1){
    // We've got IE.
}
于 2012-08-13T11:36:02.187 回答