简体   繁体   English

如何从jQuery事件处理程序中排除子元素?

[英]How to Exclude Child Element from jQuery Event Handler?

I am modifying an existing web page. 我正在修改现有网页。 I added a <textarea> to the page, but found that the Enter key doesn't work as expected. 我在页面上添加了<textarea> ,但是发现Enter键无法正常工作。

After spending considerable time searching, I found the following: 在花费大量时间进行搜索之后,我发现了以下内容:

$('form').keypress(function (e) {
    if (e.keyCode == 13)
        return false;
});

I need to leave as much as much of the existing functionality in place as I can. 我需要尽可能多地保留现有功能。 But I need to disable this for my <textarea> . 但是我需要为我的<textarea>禁用它。 (It appears mine is the only <textarea> on the page. (看来我是页面上唯一的<textarea>

But how can I do this? 但是我该怎么办呢? I thought about adding .not('textarea') to the selector above. 我考虑过将.not('textarea')到上面的选择器中。 But that doesn't work because the handler is on the form, which is not a textarea. 但这不起作用,因为处理程序位于表单上,而不是文本区域上。

I can I exclude <textarea> s from the filter above? 我可以从上面的过滤器中排除<textarea>吗?

jsBin demo jsBin演示

You can simply target the inputs 您只需定位输入

$('form input').keypress(function (e) {
    if (e.which == 13) e.preventDefault(); // Don't misuse return false
});

the textarea will go on with the enter key as usual 文本区域将照常按Enter键继续

Depends on the use-case. 取决于用例。

If you want to be sure nothing brakes use: 如果要确保没有制动器,请使用:

$('form *:not(textarea)').keypress(function (e) {
    if (e.which == 13) e.preventDefault();
});

where * targets every children, and :not selector excludes the desired one. *以每个孩子为目标,而:not选择器则排除期望的孩子。

here's another example: 这是另一个例子:

$('form *').keypress(function (e) {
    if (e.which == 13 && this.tagName!=="TEXTAREA") e.preventDefault(); 
});

You can check the if the target is the textarea : 您可以检查目标是否为textarea:

$('form').keypress(function (e) {
    if($(e.target).is('textarea')) return;
    if (e.keyCode == 13)
        return false;
});

the simplest way is to use on(), so you don't need to do any extra element comparing inside the event handler: 最简单的方法是使用on(),因此您无需在事件处理程序中进行任何额外的元素比较:

$('form').on("keypress", ":not(textarea)", function (e) {
    if (e.keyCode == 13)
        return false;
});

you use on() to watch the form, and the css selector to avoid textareas. 您可以使用on()查看表单,并使用CSS选择器避免文本区域。 to easily tweak later, you can blacklist other elements by tagname or class using more :not() operators sperated by commas. 为了以后方便地进行调整,您可以使用逗号分隔的更多:not()运算符,将标记或类的其他元素列入黑名单。 plus, on() is now recommended over the older single-purpose handlers anyway. 另外,无论如何,现在建议在较早的单一用途处理程序上使用on()。

Add a filter inside your function like this 像这样在函数内添加一个过滤器

$('form').keypress(function (e) {
    if (e.keyCode == 13 || e.target.tagName.toLowerCase() == 'textarea')
        return false;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM