检查元素是否存在导致浏览器中的脚本错误
仅当页面上存在包含某些文本的元素时,我才尝试将 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();
}
});
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.question h3:contains('Age')").length > 0 || $("div.question h3:contains('Gender')").length > 0 ) {
AddTooltips();
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
AddTooltips()
放在 dom 就绪事件之外,如下所示:put
AddTooltips()
outside the dom ready event like so: