0

我有以下 Javascript,在 id="freq-table" 的表格单元格中单击鼠标即可使用<input>单元格的值填充 id="searchTerm(x)" 的连续表单字段。它在<body>标签中被引用为:

<body onload="populateFields()>

<table>标记为:

<table onclick="populateFields()> 

var index=0;
function populateFields(){
    var ft_id = document.getElementById("freq-table");    
    var alltds = ft_id.getElementsByTagName("td");
    for (var i in alltds) {
        alltds[i].onclick = function () {
            if(index==0) {
                searchTerm1.value = this.innerHTML;
            } else {
                setThis(this.innerHTML);
            }
        }
    }
    if (index<2) {
        index++;
    } else {
        index = 1;
    }
}

function setThis(value) {
    document.getElementById("searchTerm"+index).value = value;
}

当试图通过传递元素 id(如下)使函数更通用时,现在需要第二次鼠标单击来开始填充字段。

<table onclick="populateFields(this)" id="freq-table">

function populateFields(element){
   var alltds = element.getElementsByTagName("td");

改变行为的修订是什么?我只是错误地传递了 id 吗?还是修改后的函数现在期望在<body>标签中将变量传递给它?这很令人困惑,因为:如果我错误地传递了 id,为什么该函数会在第一次鼠标单击后连续工作?请问有什么办法解决这个问题?

4

4 回答 4

2

您在这里有一些繁重的代码,其中第一个表单击(或正文加载)设置了额外的单击事件处理程序。

你应该做的是使用事件委托。通过事件委托,单击事件处理程序附加到表格,但知道单击了哪个单元格(目标)。

[更新] 基于上述文章的代码示例:

var index=0;
var tableIds=["freq-table1","freq-table2","freq-table3"];
for (var i=0;i<tableIds.length;i++) {
var currentId=tableIds[i];
var table=document.getElementById(currentId);
table.onclick = function(event) {
  event = event || window.event;
  var target = event.target || event.srcElement;
  while(target != this) {
    if (target.nodeName == 'TD') {
        // target is our cell
        setThis(target.innerHTML);
    }
    target = target.parentNode;
  }
  // increment index modulo 3
  index=(index+1)%3;
}; // end of onclick function
}  // end of for loop

现场演示:http: //jsfiddle.net/srVmF/2/

于 2013-04-17T02:55:23.373 回答
2

我认为呼叫可能来自 TD 或 TR 元素。因此,第一次 id 将是“未定义”。

为什么不使用事件调用函数并验证标签名称:

<table onclick="populateFields(event)" id="freq-table">

Javascript

function populateFields(e) { 

 var source = e.target || e.srcElement;
 if (e.tagName == 'table') {
 var ft_id = document.getElementById(source.id);
于 2013-04-17T03:09:28.457 回答
2

现在您必须在表格填充字段之前单击表格,而不是在页面加载时填充。

您可以离开页面加载处理程序:

<body onload="populateAllFields()">

为每个表添加一个类:

<table class="mytable">

然后,代码:

function populateAllFields()
{
    [].forEach.call(document.getElementsByClassName('mytable'), populateFields);
}
于 2013-04-17T03:15:13.213 回答
1

<body onload="populateFields()>没有传递您想要的元素,因此不再发生页面加载时将完成的初始设置。

您可以通过传递 ID 来修复它,并为onload处理程序提供 ID。

function populateFields(id){
    var ft_id = document.getElementById(id);    
    var alltds = ft_id.getElementsByTagName("td");
    // and so on...
}

<body onload="populateFields('freq-table')">


<table onclick="populateFields(this.id)">
于 2013-04-17T02:15:07.930 回答