Jquery:如何在函数中存储变量,并在外部使用它?

时间:2015-10-04 19:43:33

标签: javascript jquery

我正在尝试根据鼠标悬停事件更改文本:

$(document).ready(function() { 
    $('.blog_post_container').hover(function() {
        var title = $(this).find('.blog_title').text();  
        $(this).find('.blog_title').text("READ MORE >");
    }, function() {
        $(this).find('.blog_title').text(title);
    }
});

在HTML中:div.blog_title位于div.blog_post_container中。

变量“title”是在鼠标悬停时调用的函数内创建的,用于存储该特定博客文章的博客标题。我的想法是稍后使用它,当鼠标离开blog_post_container时,我不能在创建它的函数之外使用它。

我无法在该函数之前创建变量,因为它将始终返回第一篇博文的标题。

我知道解决方案很简单,但我只是找不到它。任何帮助表示赞赏!

3 个答案:

答案 0 :(得分:2)

存储标题如下:

$(this).data('blog-title', title);

然后您可以稍后通过对元素的引用来检索它:

var title = $('.blog_post_container').data('blog-title');

.data() API

答案 1 :(得分:0)

删除var以将变量附加到窗口对象

   title = $(this).find('.blog_title').text();  

如果您在准备好文档之前定义它

,那就更好了
   var title;
   //document ready code

答案 2 :(得分:0)

可能是一个过于复杂的解决方案:

#waterway

你可以像这样使用它:

function rollOver(oElem, tHoverText){
  this.tHover=tHoverText;
  this.oElem=oElem;
  this.init()
};

rollOver.prototype.init = function() {
  this.oTitle = this.oElem.querySelector('.blog_title');
  this.tTitle = this.oTitle.innerHTML;
  this.initEvents();
};

rollOver.prototype.initEvents = function() {
  var self = this;
  this.oTitle.addEventListener('mousehover', this.changeTitle.bind(this), false);
  this.oTitle.addEventListener('mouseout', this.restoreTitle.bind(this), false);
};

rollover.prototype.changeTitle = function() {
    var self = this;
    this.oTitle.innerHTML = self.tHover;
};

rollover.prototype.restoreTitle = function() {
    var self = this;
    this.oTitle.innerHTML = self.tTitle;
};

要检索标题文字,请使用var blogPost = document.getElementsByClassName('blog_post_container')[0]; var b = new rollOver(blogPost, "Read more");

相关问题