这是我拥有的桌子的基础。 它可能有更多行,name属性中的最后一个数字表示行号。我想获取最后一行内任何输入的name属性。输入是什么并不重要,因为我将分割字符串并仅保留最后一个数字。
我怎样才能做到这一点? 谢谢!
<script>
function checkInd() {
var riskind = document.getElementById("tagz").value;
if (riskind == "Attorney/ Lawyer Office" ) {
document.getElementById('highrisk').style.display = 'block';
}
else {
document.getElementById('highrisk').style.display = 'none';
document.getElementById('risk2').style.display = 'none';
}
}
</script>
<input id="tagz" name="properties[Industry]" value="" type="text" required onchange="checkInd()" onkeyup="checkInd()">
答案 0 :(得分:1)
split()
和pop()
的 :last
选择器
console.log( $("#tableNames tbody tr:last input:last").attr("name").split("_").pop())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableNames">
<tbody>
<tr>
<td>
<input type="text" name="contact1_1"/>
<input type="text" name="contact2_1"/>
<input type="text" name="contact3_1"/>
</td>
<td>
<input type="text" name="phone1_1"/>
<input type="text" name="phone2_1"/>
<input type="text" name="phone3_1"/>
</td>
</tr>
</tbody>
</table>
答案 1 :(得分:1)
$(document).ready(function() {
alert($("#tableNames").find("tr:last").find("input").attr("name"));
})
或更短的版本:
$(document).ready(function() {
alert($("#tableNames tr:last input").attr("name"));
})
这是获取最后一行输入名称的小提琴: https://jsfiddle.net/L7k2w6Ls/2/
答案 2 :(得分:1)
$('#tableNames tr:last input').map(function(){return $(this).attr('name');}).get();
答案 3 :(得分:1)
其他答案将完全按照您的要求进行。为了更有帮助,我想确保这不是XY problem。
听起来您在输入元素的名称中有效地编码了一些应用程序数据。值得一提的是,这是否是您真正想做的事情。通常我有一个与元素相关的数据,并且将jQuery的最佳位置放在元素数据数组中。即使服务器实际在名称中需要相同的信息,将数据放在javascript更容易访问的地方也可以帮助最大限度地减少将来的错误并简化您的应用程序。所以我可能会建议一个完全不同的解决方案:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableNames">
<tbody>
<tr>
<td>
<input type="text" name="contact1" data-more="1"/>
<input type="text" name="contact2" data-more="1"/>
<input type="text" name="contact3" data-more="1"/>
</td>
<td>
<input type="text" name="phone1" data-more="1"/>
<input type="text" name="phone2" data-more="1"/>
<input type="text" name="phone3" data-more="1"/>
</td>
</tr>
</tbody>
</table>
$( function(){
$("#tableNames tr:last input").each( function(){
var input = $(this);
console.log( input.attr( 'name' ) + ' has data ' + input.data( 'more' ) );
});
} );