編輯元素:如何調用觸摸或從功能單擊事件爲其生成動態
我所做的更改馬修和貝納暗示,它似乎仍然沒有工作。我在下面的帖子中編輯過的更改也是如此。
它現在的作品!感謝你們!
我對我無法解決的特定問題有疑問。如果你知道這個問題已經回答,請給我鏈接作爲答案。我試圖在這種情況下不使用框架,但如果需要可以使用jQuery。
我已經找到答案如何通過函數附加偵聽器,但我需要的東西,因爲我不會重構我已經有的所有代碼。我是一名自由職業者,正在處理別人的代碼。
發生什麼是我想要檢測觸摸設備的觸摸事件。此代碼也適用於PC,因此我需要檢測點擊次數。這個DIV是以編程方式創建的,我需要添加點擊或觸摸,具體取決於設備。最初的功能是從一個onmousedown事件事件稱爲是這樣的:
arrDivAnswers[c].onmousedown = onQuestionDown;
,這是它調用該函數:
function onQuestionDown(e)
{
if(!itemSelected)
{
if(this.getAttribute('data-isCorrect') == 'true')
setStyleQCorrect(this, true);
else
setStyleQIncorrect(this);
this.querySelector('.answerText').style.color = '#ffffff';
this.querySelector('.isCorrect').style.visibility = 'visible';
}
itemSelected = true;
}
這是工作的罰款。現在我已經制作了一個可以嘗試並選擇正確的點擊或觸摸事件的工具(我需要一個函數,因爲我必須不止一次地使用這個函數 - 而isTouchDevice工作正常,所以我在其他一些應用程序中使用它)該代碼是很短,已經過測試):
function detectEventClickOrTouch(element, functionToCall){
//detectEventClickOrTouch(arrDivAnswers[c], 'onQuestionDown');
if(isTouchDevice()){
element.addEventListener("touchend", functionToCall, false);
} else{
element.addEventListener("click", functionToCall, false);
}
}
DIV元素被這樣創造了一些循環:
arrDivAnswers[c] = document.createElement('div');
console.log("Answer object #" + c + " = " + arrDivAnswers[c]);
arrDivAnswers[c].className = 'autosize';
arrDivAnswers[c].style.textAlign = 'left';
arrDivAnswers[c].setAttribute('data-isCorrect',false);
arrDivAnswers[c].setAttribute('data-isSelected',false);
divAnswerContainer.appendChild(arrDivAnswers[c]);
然後該事件被連接到它像這樣(舊方法已被註釋掉):
for(c;c < arrQuestions[index].arrAnswers.length;c++)
{
var curAnswer = arrQuestions[index].arrAnswers[c];
arrDivAnswers[c].onmouseover = function (e){setStyleQHover(e.currentTarget)};
arrDivAnswers[c].onmouseout = function (e){setStyleQUp(e.currentTarget)};
// Detect touch here *************************
detectEventClickOrTouch(arrDivAnswers[c], onQuestionDown);
//arrDivAnswers[c].onmousedown = onQuestionDown;
// Detect touch here *************************
arrDivAnswers[c].style.visibility = 'visible';
arrDivAnswers[c].querySelector('.answerText').innerHTML = curAnswer.strAnswer;
arrDivAnswers[c].setAttribute('data-isCorrect',curAnswer.isCorrect);
if(curAnswer.isCorrect)
{
//arrDivAnswers[c].classList.add("correctAnswer");
arrDivAnswers[c].className = "correctAnswer";
}
else
{
//arrDivAnswers[c].classList.remove("correctAnswer");
arrDivAnswers[c].className = "autosize";
}
arrDivAnswers[c].setAttribute('data-isSelected',false);
setStyleQUp(arrDivAnswers[c]);
itemSelected = false;
}
[...]
調試器引發此錯誤:Uncaught TypeError: Object [object DOMWindow] has no method 'getAttribute'
我敢肯定,我搞亂了「this
」因爲我沒有正確地調用該函數。提前致謝。
我很抱歉,我不得不放棄馬修「正確答案」打勾。他在你的答案之上。我想他先到這裏。儘管如此,你們都是對的。 – HotFudgeSunday 2011-06-15 17:43:54