我必须调用一个函数将法语短语翻译成英语,并且我被卡在showEnglish()
上。它不会拉english
数组。而且我甚至不确定我是否正确引用了我在单独的JavaScript文件中设置的设置功能。</ p>
这是我到目前为止所拥有的:
window.onload = setup;
function setup() {
var questions = document.querySelectorAll("article ol li");
for (var i = 0; i < questions.length; i++){
questions[i].id = i + "phrase";
questions[i].onmousedown = showEnglish;
//questions[i].onmouseup = showFrench;
questions[i].style.cursor = "pointer";
}
}
function showEnglish() {
var phrases = document.getElementById("phrase");
var phraseNumber = parseInt(phrases.id);
phraseNumber.innerHTML = english[phraseNumber];
phraseNumber.style.fontStyle = "italic";
phraseNumber.style.fontColor = "rgb(191, 22, 31)";
}
答案 0 :(得分:0)
以下是不使用ID并且应符合您需求的示例代码段。
可以使用脚本轻松地从翻译对象构建问题列表。 (请在下面的第二个解决方案中查看代码段)
// On document load (warning: does not work with IE8)
document.addEventListener('DOMContentLoaded', function() {
setup()
})
// Store French -> English translations
var translations = {
"Comment vous appelez vous ?": "What's your name ?",
"Où habitez vous ?": "Where do you live ?"
};
// Attach `translate` function to questions `mousedown` event
function setup() {
document
.querySelectorAll("article ol li")
.forEach(function(el) {
el.onmousedown = showEnglish
});
}
// Display translation when mousedown on element
function showEnglish(event) {
var element = event.srcElement || event.target
var translation = document.getElementById("translation");
translation.innerHTML = translations[element.innerText];
}
&#13;
<html>
<head>
<style>
.question { cursor: pointer; padding: 4px }
.translation { font-style: italic; color: rgb(191, 22, 31) }
</style>
</head>
<body>
<h3>Questions</h3>
<article>
<ol>
<li class="question">Comment vous appelez vous ?</li>
<li class="question">Où habitez vous ?</li>
</ol>
</article>
<h3>Traduction</h3>
<div class="translation" id="translation"></div>
</body>
</html>
&#13;
其他解决方案
从翻译构建DOM
// On document load (warning: does not work with IE8)
document.addEventListener('DOMContentLoaded', function() {
buildDOM();
})
// Store French -> English translations
var translations = {
"Comment vous appelez vous ?": "What's your name ?",
"Où habitez vous ?": "Where do you live ?"
};
// Display translation when mousedown on element
function showEnglish(event) {
var element = event.srcElement || event.target
var translation = document.getElementById("translation");
translation.innerHTML = translations[element.innerText];
}
function buildDOM() {
var ol = document.createElement("ol");
for (var t in translations) {
var el = document.createElement("li");
el.className = "question";
el.innerText = t;
el.onmousedown = showEnglish
ol.appendChild(el);
}
document.getElementById("questions").appendChild(ol);
}
&#13;
<html>
<head>
<style>
.question { cursor: pointer; padding: 4px }
.translation { font-style: italic; color: rgb(191, 22, 31) }
</style>
</head>
<body>
<h3>Questions</h3>
<div id="questions"></div>
<h3>Traduction</h3>
<div id="translation" class="translation"></div>
</body>
</html>
&#13;