SORU
21 Aralık 2008, Pazar


-- Javascript isDOM Nasıl Javascript bir Nesne DOM Nesnesi olup olmadığını kontrol edin musun?

Almaya çalışıyorum:

document.createElement('div')  //=> true
{tagName: 'foobar something'}  //=> false

Kendi komut, hiç bir özelliği olarak tagName gerekli beri bu kullanmak için kullanılır:

if (!object.tagName) throw ...;

2 nesne için, çoğunlukla çalışan hızlı bir çözüm olarak aşağıdaki ile geldim. ;)

Sorun, tarayıcılar salt okunur değil her hangi özellikleri, zorlanarak bağlıdır.

function isDOM(obj) {
  var tag = obj.tagName;
  try {
    obj.tagName = '';  // read-only for DOM, should throw exception
    obj.tagName = tag; // restore for normal objects
    return false;
  } catch (e) {
    return true;
  }
}

Herkes iyi bir yedek olduğunu biliyor mu?

CEVAP
21 Aralık 2008, Pazar


Bu belki ilginizi çeker:

function isElement(obj) {
  try {
    //Using W3 DOM2 (works for FF, Opera and Chrom)
    return obj instanceof HTMLElement;
  }
  catch(e){
    //Browsers not supporting W3 DOM2 don't have HTMLElement and
    //an exception is thrown and we end up here. Testing some
    //properties that all elements have. (works on IE7)
    return (typeof obj==="object") &&
      (obj.nodeType===1) && (typeof obj.style === "object") &&
      (typeof obj.ownerDocument ==="object");
  }
}

DOM, Level2 bir parçası

Güncelleme 2Bu benim kendi kütüphanesinde uygulanmaktadır. (Önceki kod Düğüm ve HTMLElement beklenen nesne yerine işlevlerini olduğundan Krom işe yaramadı. Bu kod FF3 7, Chrome 1, Opera 9) test edilir

//Returns true if it is a DOM node
function isNode(o){
  return (
    typeof Node === "object" ? o instanceof Node : 
    o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
  );
}

//Returns true if it is a DOM element    
function isElement(o){
  return (
    typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
    o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName==="string"
);
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Kyler Briskey

    Kyler Briske

    20 ŞUBAT 2011
  • schmittastic

    schmittastic

    9 EYLÜL 2009
  • WiseOwlTutorials

    WiseOwlTutor

    21 EKİM 2011