这是非常基本的我肯定会使用JavaScript,但我很难受到任何帮助。
我想使用在对象的第二个子节点内发生的mouseDown事件来调用for循环中的函数。斜体的部分是我尝试这样做的。顺便说一句,swapFE功能仍在进行中。还有一件事是当我把斜体部分放在swapFE函数中时,一切都正常工作但是当我把它放在for循环中时它并不都显示出来。我不知道为什么。当我用鼠标单击短语时,我基本上会尝试将法语短语换成英语短语。
function setUpTranslation() {
var phrases = document.getElementsByTagName("p");
var swapFE = document.getElementsByTagName("phrase");
for (i = 0; i<phrases.length; i++) {
phrases[i].number = i;
phrases[i].childNodes[1].innerHTML = french[i];
*phrases[i].childNodes[1].onMouseDown = swapFE;*
}
}
/* see "function_swapFE(phrase,phrasenum);" below. The expression to call function swapFE
is located underneath "function swapFE(e)" because although the directions said to put the
"run swapFE" within the for loop it did not work properly that's why I put it beneath the
"function swapFE(e)".*/
function swapFE(e) {
var phrase = eventSource(e);
var phasenum = parseInt(1) = [1].innercontent.previousSibling;
phrase.node.previousSibling.onmousedown=swapFE
function_swapFE(e)(phrase,phrasenum);
}
}
如果您有任何疑问,请告诉我。
感谢您的帮助。
答案 0 :(得分:1)
这样,您将创建一个名为swapFE;
的局部变量var swapFE = document.getElementsByTagName( “词组”);
然后使用此方法将此var设置为mouseDown
phrase [i] .childNodes [1] .onMouseDown = swapFE; *
这不对... onMouseDown应设置为函数名,而不是该名称的局部变量。所以你应该将本地var重命名为其他东西。这至少会让你更接近解决方案。
答案 1 :(得分:0)
我只能对您的源代码可能失败的内容进行一些猜测。首先,以下代码假定所有<p>
标记都包含至少 2个子元素:
for (i = 0; i<phrases.length; i++) {
phrases[i].number = i;
phrases[i].childNodes[1].innerHTML = french[i];
*phrases[i].childNodes[1].onMouseDown = swapFE;*
}
如果页面上的任何<p>
标记少于2个子元素,则会引发错误并停止执行脚本。对此最好的解决方案是为每个<p>
标记添加一个类属性,该标记将包含您要查找的元素。或者,您可以使用if
语句检查第二个子节点是否存在。或者你可以做到这两点。
其次,与所有事件一样,onmousedown
应以小写形式声明。设置onMouseDown
不会抛出错误,而是在元素上创建自定义属性,而不是附加事件处理程序。
最后,以下代码:
var swapFE = document.getElementsByTagName("phrase");
将在本地覆盖该函数的全局函数swapFE
,而不是替换为变量。
这就是我写setupTranslation
函数的方式:
function setUpTranslation() {
var phrases = document.getElementsByTagName("p");
// rename the swapFE var as outlined below
var swapFENodes = document.getElementsByTagName("phrase");
var cNode; // set up an empty variable that we use inside the loop
for (i = 0; i<phrases.length; i++) {
/* Check for the existence of the translationPhrase class
in the <p> tag and the set the cNode var to childNodes[1]
and testing for its existence at the same time */
if (cNode.className != "translationPhrase"
|| !(cNode = phrases[i].childNodes[1]))
continue; // skip to the next iteration
phrases[i].number = i;
cNode.innerHTML = french[i];
cNode.onmousedown = swapFE; // Changed onMouseDown to onmousedown
}
}