在jquery Live中添加循环

时间:2011-01-14 21:19:51

标签: jquery

我有一个小问题。

我在所有行中重复一个表单字段,它与LIVE事件相结合以触发jQuery函数。

我能以某种方式在这里添加迭代吗?重复的代码真的不是我想要的东西......

 $("#exampassed1").autocomplete({
  source: "exams.php",
  minLength: 2
 });

 $("#exampassed2").live('focus', function() {

  $("#exampassed2").autocomplete({
  source: "exams.php",
  minLength: 2
  });

 });

 $("#exampassed3").live('focus', function() {

  $("#exampassed3").autocomplete({
  source: "exams.php",
  minLength: 2
  });

 });

 $("#exampassed4").live('focus', function() {

  $("#exampassed4").autocomplete({
  source: "exams.php",
  minLength: 2
  });

 });

 $("#exampassed5").live('focus', function() {

  $("#exampassed5").autocomplete({
  source: "exams.php",
  minLength: 2
  });

 });

 $("#exampassed6").live('focus', function() {

  $("#exampassed6").autocomplete({
  source: "exams.php",
  minLength: 2
  });

 });

 $("#exampassed7").live('focus', function() {

  $("#exampassed7").autocomplete({
  source: "exams.php",
  minLength: 2
  });

 });

 $("#exampassed8").live('focus', function() {

  $("#exampassed8").autocomplete({
  source: "exams.php",
  minLength: 2
  });

 });

 $("#exampassed9").live('focus', function() {

  $("#exampassed9").autocomplete({
  source: "exams.php",
  minLength: 2
  });

 });

 $("#exampassed10").live('focus', function() {

  $("#exampassed10").autocomplete({
  source: "exams.php",
  minLength: 2
  });

 });

我在为第一个

之后的元素思考这样的事情
 $("#exampassed2", "#exampassed3").live('focus', function() {

  $("#exampassed2").autocomplete({
  source: "exams.php",
  minLength: 2
  });

 });

 $($("#exampassed2"), $("#exampassed3")).live('focus', function() {

  $("#exampassed2").autocomplete({
  source: "exams.php",
  minLength: 2
  });

 });

 $("#exampassed2"), $("#exampassed3").live('focus', function() {

  $("#exampassed2").autocomplete({
  source: "exams.php",
  minLength: 2
  });

 });

没有完美的工作......任何人都有线索吗?

3 个答案:

答案 0 :(得分:0)

使用类而不是迭代的ids

$(".exampassed:first").autocomplete({
  source: "exams.php",
  minLength: 2
});
$(".exampassed").live('focus',function(){
  $(this).autocomplete({
    source: "exams.php",
    minLength: 2
  });
})

答案 1 :(得分:0)

您可以在引号内使用逗号来选择多个对象,如下所示:

$("#exampassed2, #exampassed3").live('focus', function() {

  $(this).autocomplete({
  source: "exams.php",
  minLength: 2
  });

 });

您不需要在live函数中重新选择jquery对象,因为$(this)选择器将引用当前对象。

有关多选择器的更多信息,请访问:http://api.jquery.com/multiple-selector/

答案 2 :(得分:0)

非常感谢Dustin和Henry的回复。

我不仅在你的帮助下解决了这个错误,还找到了如何在DatePicker上实现同样技巧的解决方案

这里是

    $(".oyekidda:first").datepicker({
        changeMonth: true,
        changeYear: true,
        yearRange: '1900:2050',
        dateFormat: 'dd/mm/yy'
});

$(".oyekidda").live('click',function(){
    $(this).removeClass('hasDatepicker').datepicker({
        showOn: 'focus',
        changeMonth: true,
        changeYear: true,
        yearRange: '1900:2050',
        dateFormat: 'dd/mm/yy'
    }).focus();
})

干杯!