jQuery选择器和$(此)

jQuery选择器和$(此),jquery,jquery-selectors,Jquery,Jquery Selectors,我有一个有趣的选择器语句: $("span#dateofbirth").bind('click', function() { $("span#dateofbirth>form>input.inplace_field").blur(); $("span#dateofbirth>form>input.inplace_field").removeClass("inplace_value"); $("span#dateofbirth>form>input.

我有一个有趣的选择器语句:

$("span#dateofbirth").bind('click', function() {
  $("span#dateofbirth>form>input.inplace_field").blur();
  $("span#dateofbirth>form>input.inplace_field").removeClass("inplace_value");
  $("span#dateofbirth>form>input.inplace_field").datepicker({dateFormat:'yy-mm-dd'});
  $("span#dateofbirth>form>input.inplace_field").addClass("inplace_value");
  $("span#dateofbirth>form>input.inplace_field").focus();
});
它实际上是由其他人插入的,以使jQueryUIDatePicker与一个原地编辑插件一起工作。它似乎更像是一个黑客/创可贴,而不是任何东西。但它是有效的

我想继续使用它,但我想对它进行修改,使其对任何带有日期的元素都更具全局性

因此,我给了span一个
.datepicker

但是,由于绑定更倾向于使用特定的ID,所以它并不能很好地定位到该元素

有没有办法解决这个问题,也许可以使用
$(this)
,与选择器语句的其余部分结合使用

也许是某种类似的东西

$("span.datepicker").bind('click', function() { 

  $(this+">form>input.inplace_field").blur();

});

选择器是普通字符串

你在试着写作

$(this).find(">form>input.inplace_field")

选择器是普通字符串

你在试着写作

$(this).find(">form>input.inplace_field")
使用
.find()

$(">form>input.inplace_field" , this)  // Provide a context to search in
JS

$("span#dateofbirth").bind('click', function() {
  $(">form>input.inplace_field" , this).blur()
          .removeClass("inplace_value")
          .datepicker({dateFormat:'yy-mm-dd'})
          .addClass("inplace_value")
          .focus();
});
您应该
链接
缓存
选择器,以减少查询DOM的次数。使用
.find()

$(">form>input.inplace_field" , this)  // Provide a context to search in
JS

$("span#dateofbirth").bind('click', function() {
  $(">form>input.inplace_field" , this).blur()
          .removeClass("inplace_value")
          .datepicker({dateFormat:'yy-mm-dd'})
          .addClass("inplace_value")
          .focus();
});

您应该
链接
缓存
选择器,以减少查询DOM的次数。子选择器现在在jQuery选择器中已被弃用(在CSS中仍然可以)

您应该使用以下内容:

$(".datepicker").on('click', function() {
  $(this).children("form").children("input.inplace_field").blur()
          .removeClass("inplace_value")
          .datepicker({dateFormat:'yy-mm-dd'})
          .addClass("inplace_value")
          .focus();
});

子选择器
现在在jQuery选择器中已被弃用(在CSS中仍然可以)

您应该使用以下内容:

$(".datepicker").on('click', function() {
  $(this).children("form").children("input.inplace_field").blur()
          .removeClass("inplace_value")
          .datepicker({dateFormat:'yy-mm-dd'})
          .addClass("inplace_value")
          .focus();
});
请注意,在许多情况下,
元素id
是不必要的,因为
元素id
是所需的全部。我认为jQuery将出于性能原因优化并丢弃
span
。但是,请避免重复地重新选择同一选择器(而不是缓存),并了解选择器序列的影响,这样总体性能会更好。请。注意,在许多情况下,
元素id
是不必要的,因为
元素id
是所需的全部。我认为jQuery将出于性能原因优化并丢弃
span
。但是,避免重复地重新选择同一个选择器(而不是缓存),并了解选择器序列的影响,这样总体性能会更好。