[英]how can i get the value of variable inside function to outside the on jquery
[英]Jquery: how can I store a variable inside a function, and use it outside?
我正在尝试根据鼠标悬停事件更改文本:
$(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 时,但我不能在创建它的函数之外使用它。
我不能在该函数之前创建变量,因为它总是会返回第一篇博客文章的标题。
我知道解决方案很简单,但我只是没有找到。 任何帮助表示赞赏!
像这样存储标题:
$(this).data('blog-title', title);
然后,您可以稍后仅通过对元素的引用来检索它:
var title = $('.blog_post_container').data('blog-title');
删除var
以将变量附加到 window 对象
title = $(this).find('.blog_title').text();
如果在文档准备好之前定义它会更好
var title;
//document ready code
也许是一个过于复杂的解决方案:
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");
要检索标题文本,请使用b.tTitle
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.