如果我想用下面的代碼放在多個DIV#ID,我該怎麼做,而不必複製代碼JQuery/Javascript - 如何最小化重複的代碼?
var scrollElem = $('#div1');
scrollElem.scroll(function() {
/* find the closest (hlisting) home listing to the middle of the scrollwindow */
var scrollElemPos = scrollElem.offset();
var newCenter = $(document.elementFromPoint(
scrollElemPos.left + scrollElem.width()/2,
scrollElemPos.top + scrollElem.height()/2)
).closest('.hlisting');
if(newCenter.is(".HighlightRow")) return;
$('.HighlightRow').removeClass("HighlightRow");
newCenter.addClass('HighlightRow');
});
我想要做的是不僅div1
執行此,也對div2
,div3
,div4
。
但正如你所注意到的,scrollElem
是一個全局變量,所以我不能只把所有這些代碼都放在1個函數中。
意義,要得到這個工作 - 我必須做的:
// DIV 2 ---------------------------
var scrollElem2 = $('#div2');
scrollElem.scroll(function() {
/* find the closest (hlisting) home listing to the middle of the scrollwindow */
var scrollElemPos = scrollElem2.offset();
var newCenter = $(document.elementFromPoint(
scrollElemPos.left + scrollElem2.width()/2,
scrollElemPos.top + scrollElem2.height()/2)
).closest('.hlisting');
if(newCenter.is(".HighlightRow")) return;
$('.HighlightRow').removeClass("HighlightRow");
newCenter.addClass('HighlightRow');
});
// DIV 3 ---------------------------
var scrollElem3 = $('#div3');
scrollElem3.scroll(function() {
/* find the closest (hlisting) home listing to the middle of the scrollwindow */
var scrollElemPos = scrollElem3.offset();
var newCenter = $(document.elementFromPoint(
scrollElemPos.left + scrollElem3.width()/2,
scrollElemPos.top + scrollElem3.height()/2)
).closest('.hlisting');
if(newCenter.is(".HighlightRow")) return;
$('.HighlightRow').removeClass("HighlightRow");
newCenter.addClass('HighlightRow');
});
這是複製和粘貼了大量的重複代碼。
問題:必須有更好的方法來做到這一點。關於如何實現相同的功能,但儘量減少代碼重複的任何想法。
必須更改對scrollElem3的引用,因爲它需要對每個對象都不相同。 $(this)好像會起作用。 – 2010-01-28 19:11:26
擊敗我。沒有理由OP給出的代碼不能放入函數中。如果有的話,最好避免全局變量。 – 2010-01-28 19:11:39
myFunc()中的scrollElem3怎麼樣? – Allen 2010-01-28 19:12:57