未捕获类型错误:不能使用'in'操作符“;使用value $(this)

"Uncaught TypeError: Cannot use 'in' operator " using value $(this)

本文关键字:使用 操作符 value this in 不能 错误 类型      更新时间:2023-09-26

当我进入页面时,在控制台中出现:Uncaught TypeError:不能使用'in'操作符在undefined中搜索'height',在值0之前(来自console.log(i);)我想在点击元素后对"I"调用ajax。我不明白为什么apapuncaught TypeError,为什么它进入loadSingleIns(I)没有任何点击。

脚本如下:

..... success: function(response) {
        console.log(JSON.parse(response));
                var instructor=JSON.parse(response);
                var el="";
        for(var i=0;i<instructor.length;i++){
             $(document).on ("click", ".insegnanti#i"+[i+1], loadSingleIns(i));
                  ....

调用的函数是:

function loadSingleIns(i){
        console.log(i);
$(this).animate({
opacity: 0.25,
left: "+=50",
height: "toggle"
}, 5000, function() {
// Animation complete.
  });
//here i want to call ajax for the element i
}

我知道有一些这样的问题,但是我找不到解决方法。

不需要在loadSingleIns函数中传递参数,在函数中元素引用和事件自动传递。

$(document).on ("click", ".insegnanti#i"+[i+1], loadSingleIns);

或者如果你真的想传递参数,那么在回调函数

中调用函数
$(document).on ("click", ".insegnanti#i"+[i+1], function(Event){
      loadSingleIns(Event, this);
});
// function with 2 params
function loadSingleIns(e, refe){
  console.log(e, refe)
}

您可能需要在调用函数loadSingleIns的第三个参数中传递处理程序引用

$(document).on ("click", ".insegnanti#i"+[i+1], loadSingleIns);

要从id中获取i,可以使用以下代码:

function loadSingleIns(){
    i = this.id.replace('i','');
}

作为一个额外的注意,你可以考虑选择器,".insegnanti#i"+[i+1]作为id应该是唯一的,你可以从选择器中删除类选择器。

正如我在注释中提到的,这段代码

for(var i=0;i<instructor.length;i++){
  $(document).on ("click", ".insegnanti#i"+[i+1], loadSingleIns(i));

除了loadSingleIns(i)问题-看起来一点也不对。你不应该这样使用类。也许你想用id属性来代替…

假设所有这些元素都已经在页面上,你可以完全摆脱循环,使用相同的类捆绑这些元素,并在一个单独的属性中使用元素的id:

HTML

<div class="insegnant" data-id="1">Element 1</div>
<div class="insegnant" data-id="2">Element 2</div>

JS

$(document).on('click', '.insegnanti', loadSingleIns);
function loadSingleIns() {
  var id = $(this).data('id');
  $(this).animate({
    opacity: 0.25,
    left: "+=50",
    height: "toggle"
  }, 5000, function() {
    // when the animation has completed run the ajax
    // this example adds the id on to the end of the URL
    // you can move this function outside of the animation if you want
    // I thought it would be better here
    $.ajax({
      url: 'http://demo.com/id=' + id
      ...
      success: function (data) {
        // do something with data
      }
    });
  });
}