如何在jquery的onclick事件中使用.each()

how to work with .each() inside a onclick event in jquery

本文关键字:each 事件 jquery onclick      更新时间:2023-09-26

我有以下情况,我不明白为什么它不工作。我在一个表中有几个<input>字段,每次用户单击其中一个输入时,我检查这个元素是否已经在这个表的输入列表中,如果不是,我就添加它。当用户在<input>元素中至少单击一次时,才正式添加到输入列表中。我这样做:

var element_input =  {"Element": ""};
var input_element = [];

$("#input"+i).click(function(){
       element_input.Element =  $(this);
       var found = false;               
       $.each(input_element,function(i){
            if(input_element[i].Element === $(this))
               input_element.splice(i,1,element_input);
               found = true;
       });
       if(!found){
         input_element.push(element_input);
       }
  });

但这绝对不起作用!我不知道哪里出了问题。他把第一个元素插入到列表中,因为它是空的,这意味着它会一直插入到代码的末尾,在同一次迭代中,它会再次进入。each循环,就像我再次点击元素,它应该开始再次读取代码,当然,他会添加这个元素,因为条件为真。最后,我得到了一个无限列表,其中多次出现相同的元素。有人能帮帮我吗?谢谢! !

对我来说,你的代码中有太多的问题,有些部分对我来说不是很清楚。这段代码:

  $.each(input_element,function(i){
        if(input_element[i].Element === $(this))
           input_element.splice(i,1,element_input);
           found = true;
   });

found总是为真,检查括号,input_element[i].Element === $(this)也总是为假,因为你比较两个对象。

这是你的例子写在更好的方式。http://jsfiddle.net/ux6hhefe/2/

更准确的解决方案是使用一个类来表示选定的元素,然后在需要时只过滤这些元素。

还可以为所有输入元素添加一个公共类,并使用它来添加click处理程序。

$(".input").click(function () {
    $(this).toggleClass('selected');
});
//then when you need to get all the selected elements
var input_element = $('.input.selected');
//if you want input_element to be an array then use
var input_element = $('.input.selected').get();

你的代码不工作,因为默认相等操作符检查对象是否通过引用相等。在您的例子中,它们总是不同的,因为每个$()调用返回一个新对象。

您可以通过一行代码检查它:

$(this)==$(this)

尝试使用this代替$(this)