我在页面上有几个
<button>
元素,我需要将距离它们最近的 <input>
元素与这些按钮关联起来。现在,当您在任何输入字段上点击 ENTER
时,它会触发表单中的第一个 <button>
。我该如何改变这个?
DOM:
<form action="irrelevant">
<div>
<select><option>1</option><option>2</option><option>3</option></select>
<input type='text'/>
<button>Hello</button>
</div>
<div>
<select><option>1</option><option>2</option><option>3</option></select>
<input type='text'/>
<button>Hello</button>
</div>
<div>
<select><option>1</option><option>2</option><option>3</option></select>
<input type='text'/>
<button>Hello</button>
</div>
<div>
<select><option>1</option><option>2</option><option>3</option></select>
<input type='text'/>
<button>Hello</button>
</div>
</form>
DOM 就绪:
$('button').click( function(){
$(this).siblings().filter('select').val('3');
return false;
});
您需要使用 KeyPress 事件来捕获按下的“Enter”键,然后使用 JavaScript 按下您想要的按钮。
例如:
//some key is pressed
$('input').keypress( function(event){
//is this "Enter"?
if (event.key === 'Enter') {
//finding the button inside the same <div> and clicking on it
$(this).parent().find('button').click();
//we don't need a default action
event.preventDefault();
}
});
类似这样的:
$('input').bind('keypress', function(e){
if(e.which == 13) { //Enter keycode
$(this).next().click()
}
return false;
});