开发者

Check if element exists causing script error in browser

开发者 https://www.devze.com 2023-01-09 12:06 出处:网络
I\'m trying to attach the Qtip plugin to elements only if the elements containing certain text exists on the page. For some reason I keep getting a script error saying \"AddTooltips() is not a functio

I'm trying to attach the Qtip plugin to elements only if the elements containing certain text exists on the page. For some reason I keep getting a script error saying "AddTooltips() is not a function." on a page where the elements do not exist. Something isn't quite working with my if statement.

$(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.que开发者_Go百科stion h3:contains('Age')").length > 0 || $("div.question h3:contains('Gender')").length > 0 ) {  
  AddTooltips();
 }
});


put AddTooltips() outside the dom ready event like so:

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();
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消