jquery插件中的全局或局部变量 [英] global or local variables in a jquery-plugin
问题描述
如何为 jquery-plugin 提供单独的局部变量,这些变量可以在不同的插件函数中访问?
How is it possible to give a jquery-plugin individual local variables, that are accessable in different plugin-functions?
我的脚本显示内容为123"的警报,但我期待的是abc".所以变量't'对于每个插件只存在一次而不是两次.因此,对于每个插件实例,还应该有一个变量 't' 的实例.
My script shows an alert with the content '123', but I am expecting 'abc'. So variable 't' exists only once and not twice for each plugin. So for each plugin-instance there should be also an instance of variable 't'.
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery/jquery-1.7.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
(function ($) {
var t = null;
$.fn.doSomething = function()
{
alert(t);
}
$.fn.myHtmlControl = function(option) {
t = option;
}
})(jQuery);
$(function () {
$('#ctrl1').myHtmlControl("abc");
$('#ctrl2').myHtmlControl("123");
$('#ctrl1').doSomething();
})
</script>
</head>
<body>
<div id='ctrl1'>Ctrl1</div>
<div id='ctrl2'>Ctrl2</div>
</body>
</html>
推荐答案
通常的方法是使用 data
函数将与特定元素相关的信息存储在元素本身上.所以在你的情况下(live example):
The usual way to do this is to use the data
function to store your information related to a specific element on the element itself. So in your case (live example):
(function ($) {
$.fn.doSomething = function()
{
alert(this.data("myHtmlControl"));
}
$.fn.myHtmlControl = function(option) {
this.data("myHtmlControl", option);
}
})(jQuery);
如果您需要存储多个选项,这里有一个更强大的示例(live copy):
If you need to store multiple options, here's a more robust example (live copy):
(function ($) {
var defaults = {
msg1: "(msg1)",
msg2: "(msg2)"
};
$.fn.doSomething1 = function()
{
alert(getOption(this, "msg1"));
return this;
}
$.fn.doSomething2 = function()
{
alert(getOption(this, "msg2"));
return this;
}
$.fn.myHtmlControl = function(options) {
this.data("myHtmlControl", $.extend({}, defaults, options));
return this;
};
function getOption(inst, name) {
var obj = inst.data("myHtmlControl");
return (obj || defaults)[name];
}
function setOption(inst, name, value) {
var obj = inst.data("myHtmlControl");
if (!obj) {
obj = $.extend({}, defaults);
inst.data("myHtmlControl", obj);
}
obj[name] = value;
}
})(jQuery);
jQuery(function($) {
$("#theButton").click(function() {
$('#ctrl1').myHtmlControl({msg1: "abc"});
$('#ctrl2').myHtmlControl({msg2: "123"});
alert("about to do ctrl1");
$('#ctrl1').doSomething1().doSomething2();
alert("about to do ctrl2");
$('#ctrl2').doSomething1().doSomething2();
});
});
这篇关于jquery插件中的全局或局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!