当你发现自己生成的飞行代码,它通常表示要退后一步,重新评估你的方法。 :-)
在这种情况下,不需要动态创建JavaScript。这只是一个运行代码的问题。
我不知道你的“积极”的定义是,所以这里的东西,消失的div输入/输出的基础上,按什么按钮:
的HTML:
<input type='button' value='1'>
<input type='button' value='2'>
<input type='button' value='3'>
<input type='button' value='4'>
<input type='button' value='5'>
<input type='button' value='6'>
<div id='container'>
<div class='c1'>This is c1</div>
<div class='c2'>This is c2</div>
<div class='c3'>This is c3</div>
<div class='c4'>This is c4</div>
<div class='c5'>This is c5</div>
<div class='c6'>This is c6</div>
</div>
JavaScript的(教学版):
jQuery(function($) {
// Hook our buttons; this selector hooks all of them,
// so you probably want to narrow that down, but I
// have no idea what your definition of "active" is,
// so I made one up.
$(":button").click(function() {
// Get the value of the button, e.g., 1, 2
var val = this.value;
// Get all of the divs in the container
var divs = $("#container div");
// Fade out all of the ones that aren't our target;
// fade in the one that is
divs.not(".c" + val).fadeOut(900);
divs.filter(".c" + val).fadeIn(900);
});
});
Live copy
,这是否:
- 使用jQuery的
ready
功能(快捷方式的形式,我只是传递函数为jQuery
功能)时,页面是“准备”来运行代码(DOM已建成)
- 查找我们想要处理的所有div。在我的情况下,它是一个容器中的所有div,但您只需使用约any CSS3 selector(and then some)。
- 使用
not
与类选择器筛选出具有目标类的div,然后使用fadeOut
开始淡出其他的。
- 使用
filter
减少设置为我们的目标div,并fadeIn
开始淡入。
该版本是为了清晰起见。这里有一个更简洁的版本(仍然非常清楚,谁知道jQuery的很好的人,但狡猾的人仍在寻找他们的脚):
中的JavaScript(使用end
链版本):
jQuery(function($) {
// Hook our buttons; this selector hooks all of them,
// so you probably want to narrow that down, but I
// have no idea what your definition of "active" is,
// so I made one up.
$(":button").click(function() {
// Get the value of the button, e.g., 1, 2
var val = this.value;
// Get all of the divs in the container
// Fade out all of the ones that aren't our target;
// fade in the one that is
$("#container div")
.not(".c" + val).fadeOut(900)
.end()
.filter(".c" + val).fadeIn(900);
});
});
Live copy
用'$('。“+ array [i] +”')替换'document.write(“$('。”+ array [i] +“')。fadeOut(900);”); 900);' – RobertPitt 2011-03-31 14:51:31
如果您定义了“活动div”,我预计会有一些提示 – Alnitak 2011-03-31 14:51:57
您要打印什么“.js”?你的'document.write'尝试看起来很狡猾。 – 2011-03-31 14:52:02