我通过一个按钮动态创建输入,一次创建两个输入,我希望每次添加一个集合时焦点都放在两个中的第一个,所以理论上它总是第二个输入
我目前使用$('input:text:visible:first').focus();
但有没有办法做到这一点,但得到倒数第二?
Input1.1
Input1.2
Input2.1
Input2.2
# user creates new input set via button
Input3.1 <---Focus on this one
Input3.2
一种解决方案是使用eq(-2).focus();
(eq() documentation)。从那里你可以看到参数可以是一个代表下一个的负数:
indexFromEnd / Type:Integer /一个整数,指示元素的位置,从集合中的最后一个元素向后计数。
我举了一个简单的例子来证明他的用法:
$("#myBtn").click(function()
{
$('<input value="new">').appendTo(".wrapper");
$('<input value="new">').appendTo(".wrapper");
$(".wrapper input").eq(-2).focus();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<input type="text" value="input1">
<input type="text" value="input2">
<input type="text" value="input3">
<input type="text" value="input4">
</div>
<button id="myBtn">ADD</button>
您可以使用input:nth-last-child(n)
,其中n是任意数字
function createInput() {
let str = `<div class ='ipCon'>
<input type='text'>
<input type='text'>
<input type='text'>
</div>`;
document.getElementById('con').innerHTML = str;
document.getElementsByClassName('ipCon')[0].querySelector('input:nth-last-child(2)').focus()
}
input:focus {
background-color: yellow;
}
<div id='con'>
</div>
<button type='button' onclick='createInput()'> Create Inputs</button>