show()和hide()的jQuery代码在控制台中工作,但在代码库中不起作用;抛出错误说“.show()和.hide()不是函数”

时间:2016-10-08 16:48:37

标签: jquery

我添加了一个包含标题的新div,我想首先隐藏它,然后在mouseenter和mouseleave上显示和隐藏。此代码在控制台中工作正常,但是当我在代码库中执行它时它不起作用。

var optly = function() {
$('.nh-copy-wrap > .title').each(function() {
if ($(this).html().indexOf('Market to a person, not a segment')>-1 && $(this).hasClass('optly') == false) {
  $("<div class= \"promo-h2\">Personalization solutions help you tailor messages to match customers across devices and channels...</div>").insertAfter(this);
  $("div.nh-promo-card-holder:contains('Market to a person, not a segment')").find("div.nh-icon.ibm-arrow-forward-link").addClass("personalization-cta");
  $(".nh-icon.ibm-marketplace-link").addClass("marketplace-logo");
  $(this).addClass('optly');
}
else if ($(this).html().indexOf('Understand and engage in the mobile moment')>-1 && $(this).hasClass('optly') == false) {
  $("<div class= \"promo-h2\">Six billion mobile devices is a big target for marketers. Mobile marketing solutions allow marketers to engage customers...</div>").insertAfter(this);
  $("div.nh-promo-card-holder:contains('Understand and engage in the mobile moment')").find("div.nh-icon.ibm-arrow-forward-link").addClass("mobile-cta");
  $(".nh-icon.ibm-marketplace-link").addClass("marketplace-logo");
  $(this).addClass('optly');
}
else if ($(this).html().indexOf('Create high performing, highly-relevant emails')>-1 && $(this).hasClass('optly') == false) {
  $("<div class= \"promo-h2\">Six billion mobile devices is a big target for marketers. Mobile marketing solutions allow marketers to engage customers through these pervasive devices with...</div>").insertAfter(this);
  $("div.nh-promo-card-holder:contains('Create high performing, highly-relevant emails')").find("div.nh-icon.ibm-arrow-forward-link").addClass("email-cta");
  $(".nh-icon.ibm-marketplace-link").addClass("marketplace-logo");
  $(this).addClass('optly');
}
});
setInterval(optly, 50);
};

var HoverOver = function() {
$(".nh-promo-card-holder").bind("mouseenter", function() {$(".promo-    h2").show();});
$(".nh-promo-card-holder").bind("mouseleave", function() {$(".promo-h2").hide();});
};

$(document).ready(function() {
optly();
setInterval(HoverOver, 200);
});

我尝试使用$(document).ready并等待新的div可用于操作,然后执行下面的代码,但是控制台仍然会抛出一个错误"...show() is not a function",同样也隐藏了。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

尝试将代码放入

$(document).ready(function(){

})

并在编写脚本之前包含jQuery

答案 1 :(得分:0)

听起来页面中的其他内容也在使用$

尝试将代码包装在:

(function($){
  /* your code */

})(jQuery);

还要确保在jQuery.js加载后加载

请注意,您还应该在找到元素时清除间隔

答案 2 :(得分:0)

这很可能是因为尚未加载jQuery。您使用jQuery的代码无法访问jQuery。结果是它无法正常工作。 要解决这个问题,你必须像Alex Muravyov所说的那样:

$(document).ready(function(){

});

并在jQuery脚本元素之后移动您的脚本元素。