2010-07-26 66 views
0

我试图将Qtip插件附加到元素只有当页面上存在包含某些文本的元素时。出于某种原因,我不断收到脚本错误,说“AddTooltips()不是一个函数。”在不存在元素的页面上。有些东西与我的if语句不太一致。检查元素是否存在导致浏览器中的脚本错误

$(document).ready(function() { 

function AddTooltips() { 
    var infoIcon = '<img class="actionItem catInfo" style="margin-left:4px" src="/images/00_Core/info.gif"/>'; 
    var $Age = $("div.question h3:contains('Age')"); 
    var $Gender = $("div.question h3:contains('Gender')"); 
    var $Questions = $("div.question h3:contains('Age'), div.question h3:contains('Gender')"); 
    $Questions.append(infoIcon); 
    $.fn.qtip.styles.speStyle = { // Last part is the name of the style 
    width: 400, 
    border: { 
    width: 2, 
    radius: 6 
    }, 
    name: 'light' // Inherit the rest of the attributes from the preset dark style 
    }; 
    $Age.children("img.catInfo").qtip({content: 'Some Copy.', style: 'speStyle' 
    }); 
    $Gender.children("img.catInfo").qtip({content: 'Some Different Copy.', style: 'speStyle' 
    }); 
} 


if ($("div.question h3:contains('Age')").length > 0 || $("div.question h3:contains('Gender')").length > 0) { 
    AddTooltips(); 
} 
}); 

回答

1

AddTooltips()的DOM已准备就绪事件外,像这样:

function AddTooltips() { 
    var infoIcon = '<img class="actionItem catInfo" style="margin-left:4px" src="/images/00_Core/info.gif"/>', 
     $Age = $("div.question h3:contains('Age')"), 
     $Gender = $("div.question h3:contains('Gender')"), 
     $Questions = $("div.question h3:contains('Age'), div.question h3:contains('Gender')"); 

    $Questions.append(infoIcon); 
    $.fn.qtip.styles.speStyle = { // Last part is the name of the style 
     width: 400, 
     border: { 
      width: 2, 
      radius: 6 
     }, 
     name: 'light' // Inherit the rest of the attributes from the preset dark style 
    }; 
    $Age.children("img.catInfo").qtip({content: 'Some Copy.', style: 'speStyle'}); 
    $Gender.children("img.catInfo").qtip({content: 'Some Different Copy.', style: 'speStyle'}); 
} 

$(function() { 
    if ($("div.question h3:contains('Age'), div.question h3:contains('Gender')").length) { 
     AddTooltips(); 
    } 
});