【问题标题】:Need "this" to reference tr and not [window object]需要“this”来引用 tr 而不是 [window object]
【发布时间】:2014-05-15 18:54:25
【问题描述】:

我有一个表格,其中的行由我的软件中的变量生成,我希望这些行在单击时突出显示。这是我的代码:

$("#varTable > tbody:last").append("<tr style='border: 1px dotted black;'  onclick=\"rowClick('" + newVariable.Name + "','" + this + "')\">><td><img id='Img12' src='images/Delete.png' width='35' height='35' style='margin-left:0px; margin-top: 10px;'></td><td>New Variable</td><td>Global</td><td></td><td><center>0</center></td><td><form action=''>" +
    "<center><input type='checkbox' name='RetainValue' value='Retain'></center></form></td><td width='100px'><button type='button' onclick='editVariable()'>Edit</button></td></tr>"); 

}

function rowClick(name, row){
console.log(row);
selectVariable = name; 
$("#selName").html("Selected Variable: <font color='red'>" + selectVariable + "</font> Filter By: <button type='button' onclick='addVariable()'>Add Variable</button>");
$(row).css("border", "1px solid black");

}

我的问题是,当我将“this”传递给函数 rowClick 时,它出现为 [window object] 而不是 onclick 所在的 tr。我也尝试使用 this.element,但表示它未定义。感谢我能得到的任何帮助。

【问题讨论】:

  • 由于您已经在使用 jQuery,您可以从标记中删除 onClick 并执行 $('body').on('click', 'tr', function(){.. . 并将新变量分配给数据属性。只是一个想法。
  • @JayBlanchard 这正是我的想法。

标签: javascript jquery this tr


【解决方案1】:

您需要将this 作为字符串的一部分传递

$("#varTable > tbody:last").append("<tr style='border: 1px dotted black;'  onclick=\"rowClick('" + newVariable.Name + "',this)\">><td><img id='Img12' src='images/Delete.png' width='35' height='35' style='margin-left:0px; margin-top: 10px;'></td><td>New Variable</td><td>Global</td><td></td><td><center>0</center></td><td><form action=''>" +
    "<center><input type='checkbox' name='RetainValue' value='Retain'></center></form></td><td width='100px'><button type='button' onclick='editVariable()'>Edit</button></td></tr>"); 

您需要在活动发生时评估this。目前,您正在追加时对其进行评估。

【讨论】:

  • +1, ... 你不需要在你的代码中写内联onclick
  • 特别是使用 jquery,您可以委托事件,以便将其应用于动态控件。
  • 好的,谢谢!这解决了它,并感谢您的建议,我会调查一下
【解决方案2】:

变化:

 rowClick('" + newVariable.Name + "','" + this + "')

到这里:

 rowClick('" + newVariable.Name + "',this)

【讨论】:

    猜你喜欢
    • 2019-09-19
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多