当事件是由单元格中的对象jQuery引起时,如何更改该单元格的自定义属性

How to change custom attribute of table cell when event was caused by object inside that cell - jQuery

本文关键字:单元格 自定义属性 何更改 jQuery 事件 对象      更新时间:2023-09-26

假设我有一个表,其中包含输入文本,下面是一个示例:

<table>
<tr><td customattribute="1"><input type='text' onchange='somefunction();'></td></tr>
<tr><td customattribute="2"><input type='text' onchange='somefunction();'></td></tr>
</table>

我有一个功能:

var myInput = something that would target td cell that is containing input causing onchange event
myInput.setAttribute('customattribute', $(this).val()); 

我想更改td的custoattrubute,它包含导致事件输入值的输入。如果不为这些元素分配id,我怎么能做到这一点呢。如何将myInput设置为"包含导致onchange事件的输入的td单元格"

我知道我应该使用$(this)和$[this]的组合。find?

您可以使用.change()和parent()之间的组合来实现

这是代码

http://jsfiddle.net/mankinchi/m4g9czc4/1/

您使用

$("input").change();

为每个输入设置一个事件。并使用

$(this).parent();

获取容器

要选择<td>,请使用.parent()函数。但是,由于您使用的是HTML函数,因此必须将this传递给该函数。试试这个:

function somefunction(myInputBox){
  var myInput = $(myInputBox).parent()[0];
  myInput.setAttribute('customattribute', $(myInputBox).val());
  //this line is just for testing.
  alert(myInput.attributes['customattribute'].value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td customattribute="1"><input type='text' onchange='somefunction(this);'></td></tr>
<tr><td customattribute="2"><input type='text' onchange='somefunction(this);'></td></tr>
</table>

您也可以使用jQuery myInput.attr()而不是myInput.setAttribute(),因此不必在parent()末尾使用[0]。(见下文)。

或者,您可以使用jQuery而不是在HTML onchange='somefunction();'中绑定click事件。这样你就不必通过this。我个人更喜欢HTML,除非出于某种原因需要在运行时绑定它。不管怎样,这取决于你:

$("input").change(function() {
  var myInput = $(this).parent();
  myInput.attr('customattribute', $(this).val());
  alert(myInput.attr('customattribute'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td customattribute="1"><input type='text'></td></tr>
<tr><td customattribute="2"><input type='text'></td></tr>
</table>