在输入标签上按Enter键后,removeEventListener onfocusout出现-错误未定义

时间:2018-07-03 13:53:06

标签: javascript jquery html ajax

这是我正确尝试的第一个javascript。

我要实现的目标:

  • 用户专注于输入元素,属性中的数据存储在变量中
  • keyup事件侦听器已添加到输入元素
  • 当用户按下Enter键时,该值通过ajax发送到数据库
  • 按下Enter键后,删除事件监听器

注意:输入元素的ID是使用php动态创建的,因此是update(this.id)的原因。

我的问题是,当我专注于元素并且我不认为removeEventListener() handler参数与addEventListener()匹配时会显示错误,是将同一处理程序与addEventListener中使用的处理程序匹配的正确方法吗?

this文章中,

  

请注意–如果我们不将函数存储在变量中,则无法删除它。

这就是为什么我将handler参数放在enter()函数中的原因。

我们非常感谢您的帮助!

其他链接:
Call Ajax when enter key pressed
removeEventListener documentation

JavaScript:

function enter() {
    function(event) {
        console.log("Key has been released")
        event.preventDefault()
        //in the event of the user releasing 'ENTER' on the keyboard
        if (event.keyCode === 13) {
            console.log("'ENTER' key pressed")
            //creates variable to store the value of the element (attribute 'value', of input element: value='". $row['may'] .""')
            var inputValue = input.value
            // alert(input.value)
            $.ajax({
                type: 'POST',
                url: 'php script/update_values.php',
                dataType: "json",
                async:false,
                data: {id : id, input : inputValue, owner : owner, monthName : monthName},
                success: function(response){
                    console.log(response.ajaxResponse)
                }
            });
        }
    }
}
//onfocus calls function with id='x' in contstructor to update score
function update(x) {
    console.log("User focused on input element.")
    //variable to assign the input element being updated 
    var input = document.getElementById(x)
    //store data in variables to be sent to script
    var id = input.getAttribute("data-id")
    var owner = input.getAttribute("data-owner")
    var monthName = input.getAttribute("data-monthName")

    //add an event listener to the input element (if a key is released executes 'function(event)')
    input.addEventListener("keyup", enter)
    input.removeEventListener("keyup", enter)

}
<input id="1" onfocus="update(this.id)" data-reference="1" data-owner="Joe Bloggs" data-monthName="dec" data-monthValue="" type="" value="220000"/>

2 个答案:

答案 0 :(得分:1)

我不确定您为什么要按原样进行操作,因为它很乱,但这是我的意见。

我分离了处理程序和事件,以便以后将其删除。


let input = document.querySelector('#myInput');
let id, owner, monthName;

let keyupHandler = e => {
  e.preventDefault();

  if (e.keyCode === 13) { // Enter key
    let inputValue = input.value;

    console.log(`Enter pressed.\nInput value: ${inputValue}\nProceeding AJAX call.`);

    $.ajax({
      type: 'POST',
      url: 'php script/update_values.php',
      dataType: "json",
      async: true, // asyn: false = deprecated
      data: {
        id: id,
        input: inputValue,
        owner: owner,
        monthName: monthName
      },
      success: function(response) {
        console.log(response.ajaxResponse);
        input.removeEventListener('keyup', keyupHandler);
        console.log("Removed keyup event");
      },
      error: function(err) {
        console.log(err);
        input.removeEventListener('keyup', keyupHandler);
        console.log("Removed keyup event");
      }
    });
  }
}

let focusHandler = e => {
  id = input.getAttribute("data-id")
  owner = input.getAttribute("data-owner")
  monthName = input.getAttribute("data-monthName")
  console.log(`Stored Data.\ndata-id: ${id}\ndata-owner: ${owner}\ndata-monthName: ${monthName}`);

  input.removeEventListener('focus', focusHandler);
  console.log("Removed focus event");
}

input.addEventListener('focus', focusHandler);

input.addEventListener('keyup', keyupHandler);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="myInput" data-id="1" data-reference="1" data-owner="Joe Bloggs" data-monthName="dec" data-monthValue="" type="" value="220000" />

答案 1 :(得分:0)

首先,在另一个函数中定义一个函数并且不在任何地方调用都没有意义。同样,如果它是一个匿名函数。但是我认为您对句子if we don’t store the function in a variable, then we can’t remove it.

感到困惑

在这种情况下,您可以在eventListener中添加一个处理函数。如果立即删除侦听器,则它没有任何作用。因此,也许您想做的就是在调用监听器处理程序后将其删除。一旦进入处理函数,您的第一个参数就是事件对象本身,因此您可以访问目标元素。然后从那里可以删除侦听器。

function enter(event) {

        console.log("Key has been released")
        event.preventDefault()
        //in the event of the user releasing 'ENTER' on the keyboard
        if (event.keyCode === 13) {
            console.log("'ENTER' key pressed")
            //creates variable to store the value of the element (attribute 'value', of input element: value='". $row['may'] .""')
            input = event.target;
            
            // alert(input.value)
            $.ajax({
                type: 'POST',
                url: 'php script/update_values.php',
                dataType: "json",
                async: false,
                data: {
                    id: input.id,
                    input: input.value,
                    owner: input.dataset.owner,
                    monthName: input.dataset.monthName
                },
                success: function (response) {
                    console.log(response.ajaxResponse)
                }
            });
        }
    input.removeEventListener("keyup", enter)
}
//onfocus calls function with id='x' in contstructor to update score
function update(input) {
    console.log("User focused on input element.", input)
    //variable to assign the input element being updated 
    
    //store data in variables to be sent to script
    var id = input.getAttribute("data-id")
    var owner = input.getAttribute("data-owner")
    var monthName = input.getAttribute("data-monthName")

    //add an event listener to the input element (if a key is released executes 'function(event)')
    input.addEventListener("keyup", enter)


}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="1" onfocus="update(this)" data-reference="1" data-owner="Joe Bloggs" data-monthName="dec" data-monthValue="" type="" value="220000"/>