請幫我找一個解決方案,使用普通的'ol JavaScript(我不能使用外部框架)。另外,CSS:懸停選擇器不適用於真實世界的實現。Javascript persistence>邏輯
繼續使用已註冊事件的某些設置將調用最後註冊的事件數組項目。
<body>
<p>When you hover over <div> tags 0-2, that <div> tag should highlight in red. Why do all of the <div> tags only affect the last <div>?</p>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<p>The same results for <p> tags.</p>
<p class="test"></p>
<p class="test"></p>
<p class="test"></p>
<script type="text/javascript">
//create arrays
var divArr = new Array();
var pArr = new Array();
//call function to populate arrays
divArr = getElementsByClassName('div','test');
pArr = getElementsByClassName('p','test');
//call function to register arrays elements events
registerArrayElementsEvents(divArr,'div');
registerArrayElementsEvents(pArr,'p');
//retrieve elements that match the passed tag and class
function getElementsByClassName(myTag,myClass) {
//load all elements into array
var elems = document.getElementsByTagName(myTag);
//create new array placeholder
var newArr = new Array();
//iterate through elements array
for (var i = 0; i < elems.length; i++) {
//check to see if element class matches parameter
if (elems[i].className == myClass){
//add matched element to new array
newArr.push(elems[i]);
}
}
//return array of matched elements
return newArr;
}
//register events to every element in the passed array
function registerArrayElementsEvents(arr,type){
//create object placeholder
var currentObj = new Object();
//iterate through the objects array
for (var i = 0; i < arr.length; i++) {
//assign current object corresponding to loop counter
currentObj = arr[i];
//write element index to element
currentObj.innerHTML = 'This is <' + type + '> ' + i;
//add mouseover event to element
addEvent(currentObj,'mouseover',function(){
//set current element color to red
currentObj.style.color = '#f00'
});
//add mouseout event to element
addEvent(currentObj,'mouseout',function(){
//set current element color to black
currentObj.style.color = '#000'
});
}
}
//register functions to events for objects
function addEvent(obj,evt,fn){
//if not IE
if (obj.addEventListener)
obj.addEventListener(evt,fn,false);
//if IE
else if (obj.attachEvent)
obj.attachEvent('on'+evt,fn);
}
</script>
</body>
首先,在求助時要彬彬有禮,第二,問一個實際的問題而不是模糊的「某些事情正在發生」。如果你有限制,說明它們。 – Oded 2011-05-03 20:34:59
坦率地說,我不明白爲什麼你不能使用jQuery。這對於JavaScript開發來說實際上是強制性的(或者至少是一個jQuery等效) – Hubro 2011-05-03 20:43:01
@Codemonkey - 我會給你一個+1,但是我找不到一個jQuery插件來做到這一點... – RobG 2011-05-03 20:52:13