动态匿名js功能无法正常工作

时间:2010-12-12 20:28:13

标签: javascript html

我的问题是我使用Javascript {调用函数addInputCompField()}动态地向HTML表添加一行。该行有2个单元格 - 第一个是一些文本,第二个是img属性。问题在于img属性,其中我还添加了一个onClick js函数,该函数将被调用以允许在用户单击图像时再次删除该行。 onClcik js函数没有像我预期的那样进行评估。

这是html代码: -

<span class="button-gray">
    <input type="button" name="" onclick="addInputCompField();"
id="Components_Button1" value="Add a Component">           

</span>

<table id="compTableId">       
</table>

这是javscript

function addInputCompField() {
    var table = document.getElementById('compTableId');
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);           
    var cell1 = row.insertCell(0);
    var newInput = document.createElement('input');
    newInput.type = "text";
    var rand_nr = Math.random();
    rand_nr = rand_nr * 100;
    rand_nr = Math.ceil(rand_nr);
    row.setAttribute('id','tr'+rand_nr);

    newInput.setAttribute('name', 'Comp-New'+rand_nr);
    newInput.setAttribute('size', '45');             
    cell1.appendChild(newInput);

    var cell2 = row.insertCell(1);           
    var newImg = document.createElement('img');
    newImg.setAttribute('src', '/img/remove_icon.png');
    newImg.height='16';
    newImg.width='16';

    var myOnClick = function() {removeCompField('tr'+rand_nr);};           
    newImg.onclick = function (){myOnClick;};

    cell2.appendChild(newImg);

    newInput.focus();                       
}

HTML和Javascript都在同一个文件中。一切正常,除非我尝试用图像点击第二个单元格以删除行。然后我得到一个浏览器错误,如下所示: -

Error: syntax error
Source File:
http://localhost....
Line: 1, Column: 9
Source Code:
function () { 

我确实需要允许用户通过执行此onClick操作来删除他们刚刚添加的行。好像没有评估javascipt当我使用firebug来查看图片中的内容时,我就是这样: -

<img height="16" width="16" 
src="/img/remove_icon.png" onclick="function () {
    removeCompField(&quot;tr&quot; + rand_nr);
}">

我原本预计不会看到rand_nr而是计算值。 关于如何解决这个问题的任何想法? - 它需要兼顾Firefox和IE。 这让我疯了!

2 个答案:

答案 0 :(得分:2)

您没有执行'myOnClick'功能。

您可以执行以下功能: newImg.onclick = function (){myOnClick();};
或者您可以直接将处理程序与函数关联: newImg.onclick = myOnClick;

答案 1 :(得分:0)

您正在错误地设置“onclick”功能。试着这样做:

newImg.onclick = function() {removeCompField('tr'+rand_nr);};

你有什么:

  var myOnClick = function() {removeCompField('tr'+rand_nr);};           
  newImg.onclick = function (){myOnClick;};

将“onclick”设置为一个根本不做任何事情的函数。

编辑 - 也许您不应该以这种方式生成行号。只需使用计数器,而不是随机数。 (您不能确定随机数生成器不会给您重复!)

相关问题