当事件是由单元格中的对象jQuery引起时,如何更改该单元格的自定义属性
How to change custom attribute of table cell when event was caused by object inside that cell - jQuery
假设我有一个表,其中包含输入文本,下面是一个示例:
<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>
相关文章:
- 设置自动分隔符的自定义属性
- 与ng attr myCustomAttribute匹配的自定义属性指令
- 获取自定义属性的值
- 如何创建自定义属性以添加if.bind
- 动态更新Angular2指令中自定义属性的值
- 使用jQuery更改输入字段的自定义属性
- 在 Javascript 生成的列表中,如何将自定义属性添加到 标记
- 设置 HTML 自定义属性与在 ID 属性中存储信息
- 是否可以在 Polymer 中的
节点上使用自定义属性以获得漂亮的 API - 为什么克隆节点排除自定义属性
- 将自定义属性添加到 vuejs 组件
- 使用原型对象向javascript对象添加自定义属性和方法的建议
- 正在设置自定义属性名称
- datalist获取选定的值和自定义属性(无事件)
- 如何使用javascript获取元素的自定义属性值
- 在jQuery方法中编写自定义属性的正确语法是什么
- 自定义属性jquery Datatables
- 使用 css() 更改自定义属性不起作用
- 警报自定义属性值 jquery 表单元格
- 当事件是由单元格中的对象jQuery引起时,如何更改该单元格的自定义属性