从输入中检索自定义属性不起作用 [英] retrieving custom attribute from input is not working
问题描述
我在具有自定义属性的<table>
中有一个<input>
标记.
当我尝试创建一个函数来检索该属性时,它不起作用.
有什么想法吗?
I've got an <input>
tag inside a <table>
with a custom attribute.
When I try to create a function to retrieve that attribute it doesn't work.
Any ideas?
<table>
<tr>
<td>
<input row="ab01" id="ab01_01">
</td>
</tr>
</table>
function retrieve_row(){
alert($(this).attr('row'));
}
结果为undefined
.为什么?
推荐答案
几件事:
您的this
范围不正确,只能直接定位您的元素:
Your this
isn't scoped right, just target your element directly:
function retrieve_row(){
alert($('#ab01_01').attr('row'));
}
此外,不要像您一样创建自定义HTML属性.不用担心,您可以使用HTML5 data-
属性来达到相同的目的:
Also, don't make custom HTML attributes like you are. Have no fear, though, you can use the HTML5 data-
attribute to achieve the same end:
<input row="ab01" id="ab01_01"> //INVALID
<input data-row="ab01" id="ab01_01"> //VALID
function retrieve_row(){
alert($('#ab01_01').attr('data-row')); //The un-hip way
alert($('#ab01_01').data('row')); //Like the cool kids are doing
}
从jQuery的pappy中获取: http://ejohn.org/blog/html-5 -data-attributes/
From jQuery's pappy: http://ejohn.org/blog/html-5-data-attributes/
基于OP的评论,我相信他正在寻找以下内容:
Based on the OP's comments, I believe he is looking for this:
$("table").on( "click", "input", function() {
alert($(this).data('row'));
});
您可能想向表中添加类或ID,以使此功能不会过于广泛.
You might want to add a class or ID to your table so that this function isn't overly broad.
这篇关于从输入中检索自定义属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!