當你發現自己生成的飛行代碼,它通常表示要退後一步,重新評估你的方法。 :-)
在這種情況下,不需要動態創建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