简体   繁体   English

模糊或按Enter时如何调用JQuery函数?

[英]How to call JQuery function when blur or press enter?

I need to release the textfield when I press enter or blur() 按Enter或blur()时需要释放文本字段

Actually I'm ok when blur(), but I need those both things. 实际上,当我使用blur()时,我还可以,但是我需要这两件事。

This is what I have: 这就是我所拥有的:

* JQuery * * jQuery *

$(document).ready(theMain);
      function theMain(){

        $("td").blur(ActTable);

        function ActTable(){
          alert("it works!");
        }

    }

* HTML * * HTML *

<table>
  <tr><td>myID</td><td>column1</td><td>column2</td></tr>
  <tr>
    <td>01</td>
    <td contenteditable="true" onkeyup="if(event.keyCode==13) ActTable();">text to change</td>
    <td contenteditable="true" onkeyup="if(event.keyCode==13) ActTable();">text to change</td>
  </tr>
</table>

In fact, this HTML part calls the function but I need to release the textfield instead of type down space. 实际上,此HTML部分调用了该函数,但我需要释放文本字段而不是向下键入空格。 Same as blur() does. 与blur()相同。

Sorry for my bad english and thanks. 对不起,我的英语不好,谢谢。

Edit: I need to release the text field when I press enter, i don't know if i'm speaking correctly but I need the same blur effect when I press enter on that textfield. 编辑:当我按Enter键时,我需要释放文本字段,我不知道我的讲话是否正确,但是在该文本字段上按Enter键时,我需要相同的模糊效果。 English is not my native language so, sorry if i'm not speaking well. 英语不是我的母语,所以抱歉,如果我说得不好。

you need to use e.which == 13 您需要使用e.which == 13

if(e.which == 13) {
    alert('You pressed enter!');
}

your code 您的代码

$(document).ready(theMain);

function theMain() {
    $("td").on('blur', ActTable).on('keypress', function (e) {
        if (e.which == 13) {
            ActTable();
        }
    });

    function ActTable() {
        alert("it works!");
    }
}

Let me know if this gets the job done as you need. 让我知道这是否可以按您的需要完成工作。

JQUERY: JQUERY:

$(document).ready(function(){
    //wire up blur events
    $('#myTable').on('blur','[contenteditable=true]',function(){
        alert('works');
    });

    //wire up keyup events
    $('#myTable').on('keyup','[contenteditable=true]',function(){
        if(event.keyCode==13){
            $(this).blur();
        }
    });
});

The only change needed on the HTML is on the table tag HTML: HTML上唯一需要的更改是在表格标签HTML上:

<table id="myTable">

Needed for the Jquery to select the tds necessary in the table. Jquery需要在表中选择必需的tds。 Also remove the onkeyup attribute on the td tags 同时删除td标签上的onkeyup属性

Have a look and tinker with it here: Fiddle 在这里看看并修改: 小提琴

Use the .keyup() method, and check if event.which equal to 13. So, you could write: 使用.keyup()方法,并检查event.that是否等于13。因此,您可以编写:

$("#yourIdHere").keyup(function (event) {
    if (event.which == 13) {
        //use blur on input
        $("#yourIdHere").blur();
    }
});

Edit 编辑

You could call the blur function after checking the event.which value. 您可以在检查event.which值后调用模糊函数。

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

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