我有一个大约有40个输入的长形式。我想听一下输入字段上的所有focusin事件,除了一个ID为“CxInfo”的div中的事件。这可能吗?
表格(伪代码)
<form>
<input type="text" name="input1" />
<input type="text" name="input2" />
... many more inputs
<div id="CxInfo"> << I want to NOT listen to focusin events on inputs in this div
<input type="text" name="fname" />
<input type="text" name="lname" />
... many more inputs
</div>
</form>
答案 0 :(得分:1)
您可以将事件委派用于form
元素,过滤掉#CxInfo
后代触发的事件:
$(myform).on('focusin', ':not(#CxInfo input)', function(e) {
/* Your code here */
});
$('#myform').on('focusin', ':not(#CxInfo input)', function(e) {
this.value = '';
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<input value="foo" />
<div id="CxInfo">
<input value="bar" />
</div>
<input value="baz" />
</form>
&#13;
或者,您可以停止在该元素内触发的事件的传播:
$('#myform').on('focusin', 'input', function(e) {
/* Your code here */
});
$('#CxInfo').on('focusin', function(e) {
e.stopPropagation();
});
$('#myform').on('focusin', 'input', function(e) {
this.value = '';
});
$('#CxInfo').on('focusin', function(e) {
e.stopPropagation();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
<input value="foo" />
<div id="CxInfo">
<input value="bar" />
</div>
<input value="baz" />
</form>
&#13;
答案 1 :(得分:0)
我无法测试它,但您可以使用$('Form > input'). On(...)
应该工作,因为它应该只针对表单的直接子项的输入,例如您的html。